C ++ STL vector container learning, stlvector

Source: Internet
Author: User

C ++ STL vector container learning, stlvector

STL (Standard Template Library) is the most important component of C ++. It provides a set of templates that represent containers, iterators, function objects, and algorithms. The container is the structure of data with the same storage type (such as vector, list, deque, set, map, etc.), and the algorithm completes specific tasks. The iterator is used to traverse container objects, act as the binder between containers and algorithms.

Template vectorIn computing, vector corresponds to an array, and its data arrangement and operation methods are very similar to array. In C ++, when using a vector Template Class, the header file must contain # include <vector> and declare the use of using std: vector or using namespace std; (1) vector InitializationTo create a vector Template object, you can use the <type> notation to specify the type used. The vector uses class function overloading and supports multiple initialization methods.
 int a[5] = {5, 1, 2, 0, 3}; vector<int> v0(a, a+4);     vector<int> v1(v0); vector<int> v2(v0.begin(), v0.begin()+2); vector<int> v3(5);
If the compiler supports C ++ 11, you can use list initialization with the same results.
 vector<int> v{5, 1, 2, 0, 3};

(2) vector Method

C ++ STL not only allocates space, but also provides some basic methods. The following describes these methods in detail. Push_backAdd an element to the end of the container. Add 1 to the number of elements in the container. Pop_backDelete the container tail element. The number of elements in the container is reduced by 1.
v1.push_back(rand()%100); v1.pop_back();
SizeNumber of current elements in the container CapacityCurrent container capacity EmptyJudge whether the container is empty
cout<<v1.size()<<endl;     cout<<v1.capacity()<<endl; if(!v1.empty()){    v1.pop_back();    cout<<"v1 is not empty!"<<endl;     }   
ResizeModify the number of elements in the current container. If the number is greater than the current number, the corresponding data is inserted. If the value is smaller than the current number, the corresponding interval is deleted. Reser VeModify the current container capacity. If the container capacity is greater than the current capacity, the corresponding space is applied. If the container capacity is smaller than the current capacity, no processing is performed.
v1.resize(9, 6);           v1.reserve(14);            
InsertInsert one or more elements in the specified range of the container EarseDelete all elements in a container or within a specified range
v0.insert(v0.begin(), a[0]);          v1.insert(v1.begin(), a, a+2);       v1.insert(v1.begin(), v0.begin()+2, v0.begin()+4);     v1.earse(v1.end()-6);                 v1.earse(v1.end()-6, v1.end());  
FrontReturns the first element of the container. BackReturns the last element of the container.
cout<<v1.front()<<endl; cout<<v1.end()<<endl;
ClearClear the elements in the container and only modify the size, without affecting the container capacity. SwapSwap the content in two containers for capacity Shrinkage
 v1.clear(); vector<int>().swap(v1);
BeginReturns the iterator pointing to the first part of the vector. EndReturns the iterator pointing to the last position of the vector. Based on the iterator, The iterator can be used to traverse the vector.
for(vector<int>::iterator iter0=vt1.begin(); iter0!=vt1.end(); iter0++){cout<<*iter0;}

Of course, C ++ 11 provides type derivation. The preceding statement can be simplified

for(auto iter0=vt1.begin(); iter0!=vt1.end(); iter0++){cout<<*iter0;}
However, if the [] operator is overloaded in vector, you can also use
for(unsinged int i=0; i<vt1.size(); i++){cout<<vt1[i];}
In the next section, we will provide Algorithms Based on STL to facilitate vector traversal and processing. (3) vector algorithms (common algorithms)STL provides a large number of algorithms for container operations. Here, we use common algorithms for_each (traversal), sort (sorting), and random_shuffle (random sorting) to demonstrate the application of STL algorithms, use the algorithm to include the header file # include <algorithm>. For_eachTraverse the container and apply the directed function to each element in the container range.
Void ShowInt (int & s) {cout <s <"";} for_each (v1.begin (), v1.end (), ShowInt ); // C ++ 11 supports lambada expressions and can be written into one sentence: for_each (v1.begin (), v1.end (), [] (int & s) {cout <s <"";});

SortThe object elements in the container are sorted according to the specified rules. By default, they are arranged in ascending order (excluding comparison functions). Of course, you can also customize comparison functions.

bool CompareInt(int &t1, int &t2){    if(t1<t2)      return true;    return false;}sort(v1.begin(), v1.end(), CompareInt); sort(v1.begin(), v1.end());//C++11 lambadasort(v1.begin(), v1.end(), [](int &t1, int &t2}->bool{        if(t1<t2)             return true;        return false;});
Lower_boundReturns the first iterator (equal or greater than) not less than the element value. The value can be inserted at the first position. Upper_boundReturns the last position where the value can be inserted without interrupting the sorting.
auto iter0 = lower_bound(v1.begin(), v1.end(), 34);cout<<*iter0<<endl;          iter0 = upper_bound(v1.begin(), v1.end(), 34);cout<<*iter0<<endl;  

Random_shuffleRandomly arrange the elements in the container. The third variable is the custom random function provided.

random_shuffle(v1.begin(), v1.end());//C++11 lambadarandom_shuffle(v1.begin, v1.end(), [](const unsigned int n)->unsigned int{        return rand()%n;});
(4) vector is used to customize data types.The vector container facilitates data sorting, insertion, deletion, and traversal operations. Combined with Operator Overloading and class template-related definitions, it is difficult to understand and manage user-defined data types through vector, but it is also used in many aspects. C ++ 11 cancels the keyword export and is not recommended. Therefore, the declaration and implementation of class templates, including the implementation of friend functions, must be declared in the same file.
/*************************************** ** # Device. h # user-defined class template # namespace user # user-defined class template device <T> # constructor overload # unary and binary operator overloading ********* * ********************************/# include <string> # include <iostream> using namespace std; namespace user {// custom class template <class T> class device {public: // The constructor loads device () {} device (T a) {id =; name = "";} device (string str) {name = str; id = 0;} device (string str, T a) {name = str; Id = ;}~ Device () {}; void show_info (); // The unary operator reloads device <T> & operator ++ (int ); // binaryoperator overload friend device <T> & operator + <T> (device <T> & d, string & s ); friend bool operator <T> (device <T> & d1, device <T> & d2); friend ostream & operator <T> (ostream & out, const device <T> & d); private: T id; string name ;}; template <class T> void device <T >:: show_info (void) {cout <"id:" <id <"; cout <" name: "<name <endl ;} template <class T> ostream & operator <(ostream & out, const device <T> & d) {out <"id:" <d. id <"name:" <d. name <"\ n"; return out;} template <class T> bool operator <(device <T> & d1, device <T> & d2) {if (d1.id <d2.id) return true; else if (d1.id = d2.id & d1.name <d2.name) return true; else return false ;} template <class T> device <T> & device <T>: operator ++ (int) {this-> id ++; return * this ;} template <class T> device <T> & operator + (device <T> & d, string & s) {d. name = s + d. name; return d ;}}

VectorDemo. cpp mainly involves smart pointers, user-defined types, and corresponding applications of STL vector containers and algorithms.

/*************************************** ** # VectorDemo. cpp # vector container method # iterator # STL algorithm # lambada expression # intelligent pointer *********************** * *******************/# include "VectorDemo. h "# include <vector> # include <iostream> # include <algorithm> # include <memory> # include" device. h "# include <string> using namespace std; using namespace user; // function template <class T> void ShowDevice (shared_ptr <device <T> & s) {cout <* s;} template <CIA Ss T> void show_genericity_demo (vector <shared_ptr <device <T> & d) {// <** three reloads: the first smart pointer and the second object, the third output is for (auto iter = d. begin (); iter! = D. end (); iter ++) {cout <** iter; // (* iter)-> show_info () ;} cout <endl ;} template <class T> bool genericity_compare (shared_ptr <device <T> & d1, shared_ptr <device <T> & d2) {// reload operator <compare if (* d1) <(* d2) return true; else return false;} // complex container vector Template, smart pointer and custom type int genericity_vector_Demo (void) {shared_ptr <device <int> spd [5] = {shared_ptr <device <int> (new device <int> ("TV", rand () % 100 )), shared_ptr <device <int> (new device <int> ("Phone", rand () % 100 )), shared_ptr <device <int> (new device <int> ("Computer", rand () % 100 )), shared_ptr <device <int> (new device <int> ("light", rand () % 100 )), shared_ptr <device <int> (new device <int> ("pot", rand () % 100),}; // create and initialize a vector container, the object is the smart pointer vector <shared_ptr <device <int> vspd (spd, spd + 5) corresponding to the device. // it traverses all objects in the vector and passes in as the shared_ptr pointer, therefore, the * number is reloaded using the <operator for_each (vspd. begin (), vspd. end (), ShowDevice <int>); cout <endl; // sort lambada expression sort (vspd. begin (), vspd. end (), [] (shared_ptr <device <int> & t1, shared_ptr <device <int> & t2)-> bool {if (* t1) <(* t2) return true; return false ;}); // arrange the random_shuffle (vspd) objects in the container in disorder. begin (), vspd. end (); show_genericity_demo <int> (vspd); cout <* vspd. front () <endl; cout <* vspd. back () <endl; vspd. push_back (shared_ptr <device <int> (new device <int> ("icebox", rand () % 100); vspd. push_back (shared_ptr <device <int> (new device <int> ("PlayStation", rand () % 100); // sort, because the container element is a smart pointer, the comparison Function Method sort (vspd. begin (), vspd. end (), genericity_compare <int>); show_genericity_demo <int> (vspd); vspd. pop_back (); show_genericity_demo <int> (vspd); // traversal ++, ++ Operator Overloading to modify the object elements in the container. for_each (vspd. begin (), vspd. end (), [] (shared_ptr <device <int> & s) {(* s) = (* s) + string ("famlily"); (* s) ++;}); show_genericity_demo <int> (vspd); return 0 ;}

Related code: container sample download

Reference books:

1. C ++ Primer Plus

2. STL source code analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.