- Introduction to Containers
- Definition and initialization
- Insert element at end
- Traversing the size function can be dynamically incremented
- Adding vector content by subscript operation is not a safe operation
- The subscript operation for an existing element only does not exist crash
- Copying an element to another container type must match the container type and the element type must be the same
- Introduction to Iterators
- Defined
- Begin and end operations
- Self-increment and dereference operations for iterators
- Arithmetic operations of iterators
- Const_iterator Read Only
Container Introduction Definition and initialization
vector<int> vec(5,100);vector<string> strVec(10,"hello");
Insert element at end
vec.push_back(102); strVec.push_back("what");
Traversing the size () function can be dynamically incremented
for( vector<int>:: Size_type ix=0; Ix<vec.size (); ix++) {cout<<vec[ix]<<endl; Vec.push_back (ix+Ten);cout<<"Size is"<<vec.size () <<endl;if(vec.size () = =Ten) { Break; } } for( vector<string>:: Size_type jx=0; Jx<strvec.size (); jx++) {cout<<strVec[jx]<<endl; }
Increase vector content by subscript operation, not safe operation
vector <int> vec2(10); cout<<vec2[9]<<endl; cout<<vec2[10]<<endl;
Only the existing elements can be subscript, there is no crash
vector<int> emptyVec;//cout<<emptyVec[0]<<endl; error
Copy element one container to another container, type must match, container type and element type must be the same
vector<int> vecCopy(vec); for(vector<int>::size_type i=0;i<vecCopy.size();i++) { cout<<vecCopy[i]<<endl; }
Introduction to Iterators
Iterators are supported for all standard library containers, but only a handful of containers support subscript operations
Defined
vector<int>::iterator iter;
Begin and end operations
Begin returns the first position that the iterator points to, and end points to the next of the vector's end elements
vector<string>::iterator iBegin=strVec.begin();vector<string>::iterator iEnd=strVec.end();
Self-increment and dereference operations for iterators
++iter points to the second element
*iter point to current element
cout<<*iBegin<<endl; cout<<*(iEnd-1)<<endl; for(;iBegin<iEnd;iBegin++) { cout<<*iBegin<<endl; }
Arithmetic operations of iterators
Iter+n Iter-n
Iter1-iter2
string str("richard"); *(iBegin+3)=str; cout<<*(iBegin+3)<<endl; cout<<iEnd-iBegin<<endl; vector<string>::iterator mid=iBegin+strVec.size()/2; cout<<*mid<<endl;
Const_iterator Read Only
Common methods of vector container