欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[C++复习]08|Templates and STL

程序员文章站 2022-03-23 14:27:23
...

[note 1]

Function templates

template <class T>
return-type function-name (arguments of type T)
{
	function body
}
在这里插入代码片

[example 1]

#include <iostream>
using namespace std;

template<class T>
void Swap(T &x, T &y)
{
	T temp=x;
	x=y;
	y=temp;
}

void fun(int m, int n,float a,float b)
{
	cout << "m and n before swap: " << m << " " << n << "\n";
	Swap(m,n);
	cout << "m and n after swap: " << m << " " << n << "\n";
	cout << "a and b before swap: " << a << " " << b << "\n";
	Swap(a,b);
	cout << "a and b after swap: " << a << " " << b << "\n";
}

int main()
{
	fun(100,200,11.22,33.44);
	return 0;
}

[note 2]

  • C++ will not perform any implicit conversion for the template arguments.

[solution 1]
explicit type conversion

cout<<"the min of 2 and 3.2 is:"<<min(double(2),3.2)<<endl;

[solution 2]
specify the argument’s data type explicitly

cout<<"the min of 2 and 3.2 is:"<<min<double>(2,3.2)<<endl;

[solution 3]
specify multiple parameters for function template.

#include<iostream>
#include<cstring>
using namespace std;

template<class T1, class T2>
void display(T1 x, T2 y){cout << x << " " << y << "\n";}

int main()
{
    display(1999,"EBG");
    display(12.34,1234);
    
    return 0;
}

[note 3]

The return type depend on the template parameter T1 (the first parameter).

[note 4]

class template

template<class T, int size>
class array
{
	T a[size];
}

to create a object:
array<int, 10> a1;

[note 5]

shows how a template function is overloaded with an explicit function.

#include<iostream>
#include<string>
using namespace std;

template<class T>
void display(T x){cout<<"Template display: "<<x<<"\n";}
void display(int x){cout<<"Explicit display: "<<x<<"\n";}	//Overloads the generic display()

int main()
{
	display(100);											//Invokes the ordinary version of display() and not the template version.
	display(12.34);
	display('C');

	return 0;
}

[note 6]

Member function templates

template<class T>
return-type classname<T>::functionname(arglist)
{
     //
}

[note 7]

Three key components of STL:

  1. containers
  2. algorithms
  3. iterators

[note 8]

STL-vector

#include<iostream>
#include<vector>									//Vector header file
using namespace std;

void display(vector<int> &v)
{
	//Size(): The member function gives the current size of the vector.
	for(int i=0;i<v.size();i++){cout << v[i] << "  ";}	
	cout << "\n";
}

int main()
{
	vector<int> v;									//Create a vector of type int
	cout << "Initial size = " << v.size() << "\n";	//Gives the current size of the vector
	//Putting values into the vector
	int x;
	cout << "Enter five integer values: ";
	for(int i=0;i<5;i++)
	{
		cin >> x;
		//member function used to put five values into the vector
		v.push_back(x);								//Takes a value as its argument and adds it to the back end of the vector.								 
	}
	cout << "Size after adding 5 values: ";
	cout << v.size() << "\n";

	//Display the contents
	cout << "Current contents: \n";
	display(v);

	//Add one more value
	v.push_back(6.6);								//float value truncated to int and then puts it into the vector at its back end(Since the vector v is of type int, it can accept only integer values )

	//Display size and contents
	cout << "\nSize = " << v.size() << "\n";
	cout << "Contents now: \n";
	display(v);

	//Inserting elements
	vector<int>::iterator itr = v.begin();			//iterator(point to the first position of the vector)
	itr = itr + 3;									//itr points to 4th element
	v.insert(itr,1,9);

	//Display the contents
	cout << "\nContents after inserting: \n";
	display(v);

	//Removing 4th and 5th elements
	v.erase(v.begin()+3,v.begin()+5);				//Removes 4th and 5th element from the vector

	//Display the contents
	cout << "\nContents after deletion: \n";
	display(v);
	cout << "END\n";
	return(0);
}

output:

Initial size = 0
Enter five integer values: 
1
2
3
4
5
Size after adding 5 values: 5
Current contents: 
1  2  3  4  5  

Size = 6
Contents now: 
1  2  3  4  5  6  

Contents after inserting: 
1  2  3  9  4  5  6  

Contents after deletion: 
1  2  3  5  6  
END

[note 9]

STL-list

#include<iostream>
#include<list>
#include<cstdlib>                //For using rand() function
using namespace std;

void display(list<int> &lst)
{
    list<int>::iterator p;
    for(p=lst.begin(); p!=lst.end(); ++p)
        cout << *p << ", ";
    cout << "\n\n";
}

int main()
{
    list<int> list1;            //Empty list1 of zero length
    list<int> list2(5);            //Empty list2 of size 5
    
    for(int i=0; i<3; i++)        //List1 filled with three values using the member function push_back() and math function rand()
        list1.push_back(rand()/100);
    
    list<int>::iterator p;
    //List2 filled using a list type iterator p and a for loop
    for(p=list2.begin(); p!=list2.end(); ++p)    //list2.begin() gives the position of the first element and list2.end() gives the position immediately after the last element.
        *p=rand()/100;
    
    cout << "List1 \n";
    display(list1);
    cout << "List2 \n";
    display(list2);
    
    //Add two elements at both the ends of list1
    list1.push_front(100);
    list1.push_back(200);
    
    //Remove an element at the front of list2(Similarly, we may use pop_back() to remove the last element.)
    list2.pop_front();
    
    cout << "Now list1 \n";
    display(list1);
    cout << "Now list2 \n";
    display(list2);
    
    list<int> listA, listB;
    //The objects of list can be initialized with other list objects illustrated as follows
    listA=list1;
    listB=list2;
    
    //Merging two lists(unsorted)
    list1.merge(list2);                    //Adds the list2 elements to the end of list1.
    cout << "Merged unsorted list2 \n";
    display(list1);
    
    //Sorting and merging
    listA.sort();        //The element in a list may be sorted in increasing order using sort() member function.
    listB.sort();        //Note that when two sorted lists are merged, the elements are inserted in appropriate locations and therefore the merged list is also a sorted one.
    listA.merge(listB);
    cout << "Merged sorted lists \n";
    display(listA);        //Display the contents of various lists.(Note the difference between the implementation of display() in Program 14.1 and Program 14.2.)
    
    //Reversing a list
    listA.reverse();
    cout << "Reversed merged list \n";
    display(listA);
    
    return(0);
}

[note 10]

STL-maps

#include<iostream>
#include<string>
#include<map>
using namespace std;

int main()
{
	string name[]={"aa","bb","cc"};
	double salary[]={1200,2000,1450};

	map<string,double>sal;
	map<string,double>::iterator p;

	for(int i=0;i<3;i++)
		sal.insert(make_pair(name[i],salary[i]));

	sal["tom"]=3400;
	sal["bob"]=2000;

	for(p=sal.begin();p!=sal.end();p++)
		cout<<p->first<<"\t"<<p->second<<endl;

	string person;
	cout<<"Name of the person to be searched: ";
	cin>>person;
	for(p=sal.begin();p!=sal.end();p++)
		if(p->first==person)
			cout<<p->second<<endl;

    return 0;
}