C++vector Basic Knowledge

Source: Internet
Author: User

Vector is the most widely used type of container in STL, and its important characteristics are summarized and summarized here. the initialization of vectors

Vector initialization, see the following code.

Vector<int> v2;       Vector with 0 element
vector<int> v3 (m);   Vector with elements whose value
is 0 vector<int> v4 (5);/vector with elements whose value is 5
  vector<int> v5{20}; Vector with 1 element whose value is
vector<int> V6 (v4);   Copy construct function
vector<int> v7 (V4.begin (), V4.end ());//construct function
Vector<int > V8 ({1,2,3,4,5});//construct a vector with initialize list vector<int> v9{1,2,3,4,5};//construct
a ve ctor with Initialize list
vector<int> v10 = {1,2,3,4,5};//Assignment construct function
the capacity and size of the vectorVectors are stored sequentially in memory, so the vector is initialized with an initial capacity (capacity), and the capacity (capacity) is similar to the maximum weight of an elevator.

When adding data to a vector, if the current element number (size) is less than capacity (capacity), the element will continue to be inserted at the appropriate location. If the current element is equal in number and capacity, the capacity of the vector is expanded, and the general capacity is increased by twice times the current amount of data.

The reserve can set the capacity of the vector, and the capacity of the vector will not shrink if the capacity to be set is less than the current capacity. If the value set is greater than the current capacity, then the set capacity is allocated. The following code:
Vector<int> v2;
V2.reserve (a);
cout << v2.capacity () << Endl;  Capacity is set to
V2.reserve (a);
cout << v2.capacity () << Endl;  Capacity is still 20
The Resize function sets the size of the vector's current number of elements, resize (n), which means that the number of elements is set to n, and if n is less than the current size, the elements that are more than n are truncated, leaving only n elements. If n is greater than the current size, the element that needs to be added defaults to 0, and if resize (n,m), the new element is initialized to M, as follows:
Vector<int> values{1,2,3};  1 2 3:size is 3
values.resize (5);           1 2 3 0 0:size is 5
values.resize (7,99);        1 2 3 0 0 99:size is 7
values.resize (6);           1 2 3 0 0 99:size is 6

Note: Resize (0) does not release memory from the vector, and the capacity of the vector has no effect, and if you want to set the vector's capacity to 0, you have the following approach: Method one: Clear and Shrink_to_fit

Vector<int> v2;
V2.reserve (a);       Capacity is set to
v2.clear ();                     
V2.shrink_to_fit (); Clear and Shrink_to_fit to set capacity to 0
Method Two: Resize and Shrink_to_fit
Vector<int> v2;
V2.reserve (a);     Capacity is set to
v2.resize (0);       Resize to is 0 element               
v2.shrink_to_fit ();//resize and Shrink_to_fit to set capacity to 0
Method Three: Swap method
Vector<int> v2;
V2.reserve (a);    Capacity is set to being
vector<int> v3;    Capacity is 0
swap (v2,v3);       V2 ' s capacity is 0
As the number of vectors is equal to the current capacity, the capacity of the vector increases as the vector increases again, usually according to the current the 50% of an existing elementTo extend, when the capacity is too large to need, you can use Shrink_to_fit () to remove excess capacity to reduce memory consumption. Vector access ElementsVectors can be accessed by using the index in square brackets or through the at (index), but the access efficiency for at is inefficient for parentheses, because the AT function checks the index for bounds, and the brackets do not check that the index is out of bounds.

The member function front () and the back () function can return a reference to the first and last element in the vector, because the reference is returned and can therefore be assigned. For example:
Vector<int> vec{1,2,3,4};
Vec.back () = m;    Set last element to
vec.front () = ten;    Set 10
The member function data () is used to return a pointer to an array that is internally used to store elements.
Vector<int> values (10,100);
Auto PData = Values.data ()//PData is a pointer point to int*
vector add element

Note: The only way to add an element to a container is to use its member functions. If you do not invoke a member function, the non-member function can neither add nor delete the element. This means that the container object must be accessed through the function he allows, and the iterator is not. Add elements. You can add an element at the end of a sequence by using the Push_back () and Emplace_back () functions of the container object. Note: Emplace_back is more efficient than push_back. This is because the parameters of the Emplace_back () are exactly the parameters that are required for the object constructor added to the container. Emplace_back generates an object in the container using its arguments as arguments to the constructor.

Vector<string> Vec;
Generates a temporary string object, and then puts the temporary object into the vector end
vec.push_back ("Hello World1");
A constructor that is passed directly as a parameter to the end string does not produce a temporary object this step
vec.emplace_back ("Hello world2");
String Str ("to Yes or not");
Emplace_back () a parameter
vec.emplace_back (str,0,18) that is required to directly pass the constructor of a string;

Inserts an element. You can insert a new element in a vector sequence by emplace () the member function. Objects are generated directly in the container, rather than first generating the object individually, and then passing it as a parameter. The first parameter of Emplace () is the insertion position of the specified object, followed by the parameters that are required to construct the object, and the parameters that are passed in are different depending on the type of object stored in the vector.

Insert () with a member function inserts one or more elements in the vector, and the first argument is always a const or non-const iterator that points to the insertion point. The element is quickly inserted before the element that the first argument points to, and if the first argument is a reverse iterator, the element is inserted behind the element that the iterator points to. code example below.

Vector<string> v2;
V2.emplace_back ("second");              Second
string str1 = "a";  
V2.emplace (V2.begin (), str1);           The second     
string str2 = "Third";
V2.emplace (V2.begin () + 1,  str2,  0,  5);  The third second
V2.emplace (V2.begin () +1, 4, ' Z ');           
Insert a single element, insert the second parameter to specify the value to insert. Insert inserts a single element with two overloaded version functions, the first parameter of two functions specifies the insertion position, and the second parameter specifies the insertion element. The first version inserts the element type as const T&amp, and the second version of the type is a t&&--right value reference. The right value reference object is a temporary object, so the insertion is moved instead of copied into the insert process. Note: Using the same parameters, invoking insert () does not invoke emplace () efficiently. The following function, which invokes the insert, generates a temporary object as the second argument passed in, but in the Emplace () call, the constructor generates a string object directly in the container with the second argument. The following code:
Vector<string> words {"One", "three", "eight"};

Iter1 point to Elment being inserted
auto Iter1 = Words.insert (Words.begin () +1, "two")//t&& version,one TW O three eight,

Words.emplace (Words.begin () +1, "two");/more effective than insert.
String str = "Nine";
Iter2 point to Elment being inserted//cosnt t& Version,one Two three-eight nine
auto iter2 = Words.insert (Words.end (), str);
Inserts a sequence of elements. The Insert function can insert a series of elements before a specific location. This is a function that the Emplace function does not have。 When you insert a series of elements, insert returns the position of the first inserted element.
String more[] = {"Five", "six", "Seven"};
vector<string> words;
Words.insert (Words.begin (), Begin (more), end (more));
Words.insert (Words.end (), {"Some", "one", "like", "You"});
Words.insert (Wrods.begin () +1,5, "forward");    Insert 5 "Forward"
vector Delete elementUse the clear function to empty the elements in the vector, but capacity is not released. Use Pop_back () to delete container tail elements. If you want to delete an element from a location in the vector, you can swap with swap and the last element, and then use Pop_back () to delete the last element. code example below.
Vector<int> VEC = {1,3,5,7,9};
Vec.swap (Vec.begin () +1,vec.end ()-1);
Vec.pop_back ();     Remove 3

The member function erase can be used to delete one or more elements in a container, and if you only need to delete an element, provide an iterator location, delete the element and return the iterator that deletes the next position of the element. If you need to delete a range of elements, you need to provide two parameters, that is, to delete the start and end of the range.

The Remove () algorithm deletes elements that match a specific value within a specified range . But remove () is a global function and cannot delete elements in the container. Remove first looks in the vector for the element to be deleted, then moves all elements after the element forward to overwrite the element, and the last element value to be deleted is set to the default value. It should be noted that the Remove () function does not change the size and capacity of the vector, so in order to remove the redundant location, it needs to be used with erase. The sample code is as follows:

Vector<string> VEC = {"One", "none", "some", "all", "none", "most", "many"};
Auto iter = Remove (Words.begin (), Words.end (), "none");
Words.erase (Iter,words.end ());//remove surplus elements
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.