C++ | C++ STL vector container details (sequence)

C++ | C++ STL vector container details

Detailed explanation of C++ STL vector container

The vector container is STL One of the most commonly used containers in. It is very similar to the array container and can be regarded as a pair of containers C++ "Upgrade" of normal array. The difference is that array implements a static array (an array with fixed capacity), while vector implements a dynamic array, that is, elements can be inserted and deleted. In this process, vector will dynamically adjust the memory space occupied, and there is no need for manual intervention in the whole process.

Vector is often called a vector container, because it is good at inserting or deleting elements at the tail. It can be completed in constant time, and the time complexity is O(1); For inserting or deleting elements in the head or middle of the container, it takes longer (moving elements takes time), and the time complexity is linear order O(n).

Standard library header <vector>

Several ways to create vector containers

  1. Create a vector container that stores elements of type double:

std::vector<double> values;

Note that this is an empty vector container, because there are no elements in the container, so no space is allocated for it.
When you add the first element (such as using the push_back() function), the vector automatically allocates memory.

On the basis of creating an empty container, you can also increase the capacity of the container by calling the reserve() member function as follows:

values.reserve(20);

This sets the memory allocation of the container, that is, it can hold at least 20 elements.
Note that if the capacity of the vector is greater than or equal to 20 elements before executing this statement, the statement will do nothing;
In addition, calling reserve() will not affect the stored elements, nor will it generate any elements, that is, there are still no elements in the values container at this time.

Note: if reserve() is called to increase the capacity of the container, any iterators previously created (such as the start iterator and the end iterator) may become invalid, because in order to increase the capacity of the container, the elements of the vector < T > container may have been copied or moved to a new memory address. So when you use these iterators later, it's best to regenerate them.

  1. Specify the initial value and the number of elements while creating:

std::vector<int> values = {1, 2, 4, 88, 99};//vector container with 5 elements
  1. Specify the number of elements when creating:

std::vector<int> values(20);//It contains 20 elements, and the default initial value is 0

Note: there is a difference between parentheses () and braces {}. The former (for example, (20)) indicates the number of elements, while the latter (for example, {20}) indicates that there is only one element 20 in the vector container.

If you do not want to use 0 as the default value, you can also specify another value, for example:

std::vector<int> values(20, 1);//The second parameter specifies that the initial value of all elements is 1
int num=20;
double value =1.0;
std::vector<double> values(num, value);//The two parameters can be variables
  1. You can also create a new vector container by storing other vector containers with the same element type:

std::vector<char>value1(5, 'c');
std::vector<char>value2(value1);

Thus, the value2 container also has five characters' c '.

On this basis, if you do not want to copy all the elements in other containers, you can use a pair Pointer Or iterator to specify the range of initial values, for example:

int array[]={1,2,3};
std::vector<int>values(array, array+2);//values will save {1,2}
std::vector<int>value1{1,2,3,4,5};
std::vector<int>value2(std::begin(value1),std::begin(value1)+3);//value2 save {1,2,3}

The vector container contains member functions

Function memberFunction function
begin()Returns an iterator that points to the first element in the container.
end()Returns an iterator that points to the location after the last element of the container, usually used in conjunction with begin().
rbegin()Returns an iterator pointing to the last element.
rend()Returns an iterator that points to the previous position of the first element.
cbegin()The function is the same as that of begin(), but the const attribute is added on the basis of it and cannot be used to modify elements.
cend()The function is the same as that of end(), but the const attribute is added on the basis of it and cannot be used to modify elements.
crbegin()It has the same function as rbegin(), but the const attribute is added on it, which can not be used to modify elements.
crend()The function is the same as that of rend(), but the const attribute is added on the basis of it, which can not be used to modify elements.
size()Returns the actual number of elements.
max_size()Returns the maximum number of elements. This is usually a large value, usually 232-1, so we rarely use this function.
resize()Change the number of actual elements.
capacity()Returns the current capacity.
empty()Judge whether there are elements in the container. If there are no elements, return true; Otherwise, false is returned.
reserve()Increase the capacity of the container.
shrink _to_fit()Reduces memory to a size equal to the size actually used by the current element.
operator[ ]The [] operator is overloaded, and the elements in the vector container can be accessed or even modified through subscripts, just like the elements in the array.
at()Access elements using a bounds checked index.
front()Returns a reference to the first element.
back()Returns a reference to the last element.
data()Returns a pointer to the first element in the container.
assign()Replace the original content with a new element.
push_back()Add an element at the end of the sequence.
pop_back()Remove the element at the end of the sequence.
insert()Inserts one or more elements at the specified location.
erase()Remove an element or a segment of elements.
clear()Remove all elements and the container size becomes 0.
swap()Swap all elements of the two containers.
emplace()Generates an element directly at the specified location.
emplace_back()Generate an element at the end of the sequence.

The C++ 11 standard library also adds two new functions, begin() and end(). Unlike the begin() and end() member functions contained in the vector container, the operation objects of these two functions provided by the standard library can be containers or ordinary arrays. When the operation object is a container, it has exactly the same functions as the begin() and end() member functions contained in the container; If the operand is an ordinary array, the begin() function returns a pointer to the first element of the array. Similarly, end() returns a pointer to a position after the last element in the array (note that it is not the last element).

The vector container also has an STD:: swap (x, y) non member function (where x and y are vector containers that store elements of the same type). It has exactly the same function as the swap() member function, except for syntax differences.

Instance 1(push_back(), size(), begin(), end(), at(), insert())

/*******************************************************************
 *   > File Name: stl-vector.cpp
 *   > Create Time: 2021 October 10, 2012 12:44:11
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<char> value; // Initialize an empty vector container
    value.push_back('S');// Add element'S'
    value.push_back('T');// Add element'T '
    value.push_back('L');// Add element 'L'

    printf("Number of elements:%ld\n", value.size());// Actual number of elements

    for(auto i = value.begin(); i < value.end(); i++){
        cout << *i << " " ;// Output element
    }
    cout << endl;// Line feed

    value.insert(value.begin(), 'C');// Insert element first
    cout << "First element:" << value.at(0) << endl;// Access elements using at()

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day15> .\stl-vector.exe
 Number of elements: 3
S T L
 First element:C

C++ STL vector container iterator usage details

vector supports member functions of iterators:

Member functionfunction
begin()Returns a forward iterator pointing to the first element in the container; If it is a const type container, the function returns a constant forward iterator.
end()Returns a forward iterator pointing to a position after the last element of the container; If it is a const type container, the function returns a constant forward iterator. This function is usually used with begin().
rbegin()Returns a reverse iterator pointing to the last element; If it is a const type container, the function returns a constant inverse iterator.
rend()Returns a reverse iterator pointing to a position before the first element. If it is a const type container, the function returns a constant inverse iterator. This function is usually used with rbegin().
cbegin()The function is similar to begin(), except that the iterator type returned is a constant forward iterator and cannot be used to modify elements.
cend()It has the same function as end(), except that its returned iterator type is a constant forward iterator and cannot be used to modify elements.
crbegin()It has the same function as rbegin(), except that the iterator type it returns is a constant reverse iterator and cannot be used to modify elements.
crend()The function is the same as that of rend(), except that the iterator type returned is a constant reverse iterator and cannot be used to modify elements.

The global functions begin () and end () newly added in C++ 11 are also applicable to the vector container. That is, when the operation object is a vector container, its functions are the same as the begin() and end() member functions in the above table.

When the above functions are actually used, their return value types can be replaced by the auto keyword, and the compiler can determine the type of the iterator by itself.

Basic usage of vector container iterators

Instance 2 (begin() and end())

/*******************************************************************
 *   > File Name: stl-vector-begin-end.cpp
 *   > Create Time: 2021 November 10, 2014 20:08:03
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>values{1, 2, 3, 4, 5};
    auto first = values.begin();
    auto end = values.end();

    while(first != end){
        cout << *first << " ";
        ++ first;
    }

    return 0;
}

Compile and run:

PS E:\fly-prj\cplusplus\day33> make 
g++ -o stl-vector-begin-end stl-vector-begin-end.cpp -g -Wall -std=c++11   
PS E:\fly-prj\cplusplus\day33> .\stl-vector-begin-end.exe
1 2 3 4 5

At the same time, you can also use the global begin() and end() functions to get iterators from the container.

auto first = std::begin(values);
auto end = std::end(values);

The only difference between cbegin()/cend() member functions and begin()/end() is that the former returns a const type forward iterator, which means that the iterators returned by cbegin() and cend() member functions can be used to traverse elements in the container or access elements, but the stored elements cannot be modified.

Example 3(cbegin() and cend())

//*******************************************************************
 *   > File Name: stl-vector-cbegin-cend.cpp
 *   > Create Time: 2021 20:15:24, November 10
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>values{1 ,2 ,3 , 4 ,5};
    auto first = values.cbegin();
    auto end = values.cend();

    while(first != end){
        cout << *first << " ";//Cannot be modified * first
        ++ first;
    }
    cout << endl;

    return 0;
}

Compile and run:

PS E:\fly-prj\cplusplus\day33> make
g++ -o stl-vector-cbegin-cend stl-vector-cbegin-cend.cpp -g -Wall -std=c++11
PS E:\fly-prj\cplusplus\day33> .\stl-vector-cbegin-cend.exe
1 2 3 4 5

The vector template class also provides rbegin() and rend() member functions, which respectively represent random access iterators pointing to the last element and the position before the first element, also known as reverse iterators.

Instance 4 (reverse iterators rbegin() and rend())

/******************************************************************* 
*   > File Name: stl-vector3.cpp 
*   > Create Time: 2021 October 10, 2014 18:54:46 
******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[]){    
    vector<int> values{1, 2, 3, 4, 5};    
    auto first = values.rbegin();    
    auto end = values.rend();    
    while(first != end){        
        cout << *first << ' ';        
        ++first;    
    }    
    cout << endl;
    
    return 0;
}

Compile and run:

PS D:\study\cplusplus\day15> make stl-vector3
g++ -o stl-vector3 stl-vector3.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day15> .\stl-vector3.exe
5 4 3 2 1

The uniqueness of vector container iterators

Unlike the array container, the vector container can apply for more storage space with the increase of storage elements.
Therefore, when creating a vector object, we can directly create an empty vector container without affecting the subsequent use of the container.

However, this creates a problem that iterators cannot be used when initializing an empty vector container.
That is to say, the following method of initializing the vector container does not work:

Instance 5 (empty vector container, iterators are not allowed)

/*******************************************************************
 *   > File Name: stl-vector4.cpp
 *   > Create Time: 2021 October 10, 2014 20:04:57
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values;
    int val = 1;
    for(auto first = values.begin(); first < values.end(); ++first, val ++){
        *first = val;// invalid
        cout << *first;// No output
    }

    return 0;
}

Compile and run (no output):

For an empty vector container, the iterators returned by the begin() and end() member functions are equal, that is, they point to the same location.

Therefore, for an empty vector container, you can call push_back() or use the resize() member function to initialize the container.

When the vector container requests more memory, all elements in the container may be copied or moved to a new memory address, which will invalidate the iterator previously created.

Instance 6 (reserve())

/*******************************************************************
 *   > File Name: stl-vector.cpp
 *   > Create Time: 2021 October 12, 2014 0:43:34
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1, 2, 3};
    cout << "The addr of values[0]: " << values.data() << endl;
    auto first = values.begin();
    auto end = values.end();
    values.reserve(20);// Increase the capacity of values to 20
    cout << "The addr of values[0]: " << values.data() << endl;
    //first = values.begin();
    //end = values.end();
    while(first != end){
        cout << *first;
        first ++;
    }
    cout << endl;

    return 0;
}

Compile and run (the running result may be wrong):

PS E:\MyStudy\cplusplus\day02> make 
g++ -o stl-vector stl-vector.cpp -g -Wall -std=c++11
PS E:\MyStudy\cplusplus\day02> .\stl-vector.exe
The addr of values[0]: 0xfb0590
The addr of values[0]: 0xfb1c70
16455520164497283

Instance 7 (iterator reinitialization)

After the values container increases its capacity, the storage address of the first element changes. At this time, it is obviously wrong to use the iterator created earlier. Therefore, to be on the safe side, whenever the capacity of the vector container changes, we need to reinitialize the iterator we created earlier:

/*******************************************************************
 *   > File Name: stl-vector.cpp
 *   > Create Time: 2021 October 12, 2014 0:43:34
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1, 2, 3};
    cout << "The addr of values[0]: " << values.data() << endl;
    auto first = values.begin();
    auto end = values.end();
    values.reserve(20);// Increase the capacity of values to 20
    cout << "The addr of values[0]: " << values.data() << endl;
    /*The capacity has changed, the memory has been reapplied, and the iterator needs to be reinitialized*/
    first = values.begin();
    end = values.end();
    while(first != end){
        cout << *first;//Output element
        first ++;
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector
g++ -o stl-vector stl-vector.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector.exe
The addr of values[0]: 0x800062170
The addr of values[0]: 0x800084640
123

Several ways of accessing elements in C++ STL vector container

Access a single element in the vector container

Access the stored elements like an ordinary array and modify the elements at the specified subscript:

Instance 8 (accessed with subscript [])

/*******************************************************************
 *   > File Name: stl-vector1.cpp
 *   > Create Time: 2021 October 12, 2014 1:06:05
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1, 2, 3, 4, 5};
    cout << values[0] << endl;
    values[0] = values[1] + values[2] + values[3] + values[4];
    cout << values[0] << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector1
g++ -o stl-vector1 stl-vector1.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector1.exe
1
14

Note: container name [n] is a way to obtain elements. It is necessary to ensure that the value of subscript n does not exceed the capacity of the container (which can be obtained through the capacity() member function), otherwise an out of bounds access error will occur. The vector container provides the at() member function. When the index passed to at() is out of bounds, STD:: out will be thrown_ of_ Range exception.

Instance 9 (accessed using the at() function)

/*******************************************************************
 *   > File Name: stl-vector-at.cpp
 *   > Create Time: 2021 October 14, 2014 23:14:53
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1,2,3,4,5};

    cout << values.at(0) << endl;
    values.at(0) =  values.at(1) + values.at(2) + values.at(3) + values.at(4);
    cout << values.at(0) << endl;
    cout << values.at(6) << endl; /*Throw exception*/
    cout << "END.\n";

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-at
g++ -o stl-vector-at stl-vector-at.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> .\stl-vector-at.exe
1
14
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 6) >= this->size() (which is 5)
      1 [main] stl-vector-at 164 cygwin_exception::open_stackdumpfile: Dumping stack trace to stl-vector-at.exe.stackdump

The front() and back() functions return the reference of the first and last element in the vector container respectively. Through the reference, you can access (or even modify) the first and last elements in the container.

Instance 10 (using the front() and back() functions)

/*******************************************************************
 *   > File Name: stl-vector-front.cpp
 *   > Create Time: 2021 October 14, 2014 23:26:14
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1,2,3,4,5};
    cout << "values First element:" << values.front() << endl;
    cout << "values Tail element:" << values.back() << endl;

    values.front() = 10;
    values.back() = 100;
    cout << "values New header element:" << values.front() << endl;
    cout << "values New tail element:" << values.back() << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-front
g++ -o stl-vector-front stl-vector-front.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> .\stl-vector-front.exe
values First element:1
values Tail element:5
values New header element:10
values New tail element:100

Accessing multiple elements in the vector container

To access multiple elements in the vector container, you can use the size() member function, which can return the number of elements actually stored in the vector container.

Instance 11 (using the size() function)

/******************************************************************* 
*   > File Name: stl-vector-size.cpp 
*   > Create Time: 2021 October 16, 2011 11:41:07 
******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[]){    
    vector<int> values{1,2,3,4,5};    
    for(long unsigned int i=0; i < values.size(); i++){        
        cout << values[i] << " ";    
    }    
    cout << endl;    
    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-size
g++ -o stl-vector-size stl-vector-size.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector-size.exe
1 2 3 4 5

Note: do not use the capacity() member function here, because it returns the capacity of the vector container rather than the number of actual storage elements. There is a difference between the two

Example 12 (range based loop)

/*******************************************************************
 *   > File Name: stl-vector-auto.cpp
 *   > Create Time: 2021 October 16, 2012 12:18:52
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1,2,3,4,5};
    /*Range based loop*/
    for(auto&& value: values){
        cout << value << ' ';
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-auto
g++ -o stl-vector-auto stl-vector-auto.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector-auto.exe
1 2 3 4 5

Instance 13 (using iterators)

Use the vector iterator to traverse the vector container.

/*******************************************************************
 *   > File Name: stl-vector-iterator.cpp
 *   > Create Time: 2021 October 16, 2012 12:27:16
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int> values{1,2,3,4,5};
    for(auto first = values.begin(); first < values.end(); ++first){
        cout << *first << " ";
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-iterator
g++ -o stl-vector-iterator stl-vector-iterator.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector-iterator.exe
1 2 3 4 5

The difference between C++ vector capacity and size

Vector container capacity (expressed in capacity) refers to the maximum number of elements that can be saved by the container without allocating more memory; The size of the vector container (expressed in size) refers to the number of elements it actually contains.

Instance 13(capacity() and size() functions)

/*******************************************************************
 *   > File Name: stl-vector-reserve.cpp
 *   > Create Time: 2021 October 16, 2014 17:48:17
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    std::vector<int>values{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47};
    values.reserve(20);
    cout << "values capacity:" << values.capacity() << endl;
    cout << "values size:" << values.size() << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-reserve
g++ -o stl-vector-reserve stl-vector-reserve.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> ./stl-vector-reserve.exe
values capacity:20
values size:15

Obviously, the size of the vector container cannot exceed its capacity. On the basis that the size is equal to the capacity, as long as one element is added, more memory must be allocated. Note: the "more" here is not one. In other words, when the size and capacity of the vector container are equal, if another element is added (or inserted) to it, the vector will often apply for multiple storage spaces, not just one.

Once the memory of the vector container is reallocated, all references, pointers and iterators related to the elements in the vector container may become invalid. The safest way is to regenerate.

Example 14

/*******************************************************************
 *   > File Name: stl-vector-capacity.cpp
 *   > Create Time: 2021 October 16, 2013 21:59:15
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>values{2,3,5,7,11,13,17,19,23,29,31,37,41,43,47};
    cout << "values capacity:" << values.capacity() << endl;
    cout << "values size:" << values.size() << endl;
    printf("values address:0X%lX\n", values.data());
    values.push_back(53);
    cout << "values Capacity 1:" << values.capacity() << endl;
    cout << "values Size 1:" << values.size() << endl;
    printf("values Address 1:0X%lX\n", values.data());
    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> ./stl-vector-capacity.exe
values capacity:15
values size:15
values address:0X800062170
values Capacity 1:30
values Size 1:16
values Address 1:0X8000846A0

You can see that adding another element to the "full" vector container changes the storage location of the entire value container, and the vector will apply for multiple storage spaces at one time (the specific amount depends on the implementation of the underlying algorithm). The advantage of this is that it can greatly reduce the number of times vector applies for space. When subsequent elements are added, it can save the time spent in applying for space.

Therefore, for the vector container, when adding new elements, it may be completed quickly (i.e. directly in the reserved space); It may also be slower (add new elements after capacity expansion)

Modify the capacity and size of the vector container

Instance 15 (resize() function)

/*******************************************************************
 *   > File Name: stl-vector-resize.cpp
 *   > Create Time: 2021 October 16, 2012 22:19:19
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>values{ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 };
    cout << "values Capacity:" << values.capacity() << endl;
    cout << "values size:" << values.size() << endl;
    for(auto&& value: values){
        cout << value << " " ;
    }
    cout << endl;

    values.reserve(20);
    cout << "values Capacity 1:" << values.capacity() << endl;
    cout << "values Size 1:" << values.size() << endl;
    for(auto&& value: values){
        cout << value << " " ;
    }
    cout << endl;

    /*Change the number of elements to 21, so 6 default initialized elements will be added*/
    values.resize(21);
    cout << "values Capacity 2:" << values.capacity() << endl;
    cout << "values Size 2:" << values.size() << endl;
    for(auto&& value: values){
        cout << value << " " ;
    }
    cout << endl;

    /*Change the number of elements to 25, so 4 default initialized elements will be added*/
    values.resize(25,99);
    cout << "values Capacity 3:" << values.capacity() << endl;
    cout << "values Size 3:" << values.size() << endl;
    for(auto&& value: values){
        cout << value << " " ;
    }
    cout << endl;

    /*Reduce container size*/
    values.resize(10);
    cout << "values Capacity 4:" << values.capacity() << endl;
    cout << "values Size 4:" << values.size() << endl;
    for(auto&& value: values){
        cout << value << " " ;
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day16> make stl-vector-resize
g++ -o stl-vector-resize stl-vector-resize.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day16> .\stl-vector-resize.exe
values Capacity: 15
values Size: 15
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
values Capacity 1:20
values Size 1:15
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
values Capacity 2:30
values Size 2:21
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 0 0 0 0 0 0
values Capacity 3:30
values Size 3:25
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 0 0 0 0 0 0 99 99 99 99
values Capacity 4:30
values Size 4:10
2 3 5 7 11 13 17 19 23 29

You can see that the size of the value container does not change only by increasing the capacity of the value container through the reserve() member function; However, by changing the size of the value container through the resize() member function, its capacity may change. In addition, it should be noted that reducing the size of the container through the resize() member function (redundant elements will be deleted directly) will not affect the capacity of the container.

vector data type for container capacity and size

In the actual scene, we may need to save the capacity and size of the container in variables. We should know that the capacity and size type of the vector < T > object are vector < T >:: size_ Type. Therefore, when defining a variable to save these values, it can be as follows:

vector<int>::size_type cap = value.capacity();
vector<int>::size_type size = value.size();

size_ The type type is defined in the vecotr class generated by the vector class template. The real type it represents is related to the operating system. In 32-bit architecture, it generally represents unsigned int type, while in 64 bit architecture, it generally represents unsigned long type.

You can use the auto keyword instead of vector < int >:: size_ type.

auto cap = value.capacity();
auto size = value.size();

Deep analysis of the underlying implementation mechanism of C++ vector container

Among many STL containers, vector is one of the most commonly used containers. The data structure adopted at the bottom is very simple, just a continuous linear memory space.

By analyzing the source code of the vector container, it can be found that it is represented by three iterators (which can be understood as pointers):

//_ Alloc represents the memory allocator. This parameter hardly needs our attention
template <class _Ty, class _Alloc = allocator<_Ty>>
class vector{    
    ...protected:    
    pointer _Myfirst;    
    pointer _Mylast;    
    pointer _Myend;
};

Among them_ Myfirst points to the starting byte position of the vector container object;
_ Mylast refers to the last byte of the current last element;
_ Myend points to the last byte of the memory space occupied by the entire vector container.

On this basis, combining the three iterators in pairs can also express different meanings, such as:

  • _ Myfirst and_ Mylast can be used to represent the memory space currently used in the vector container;
  • _ Mylast and_ Myend can be used to represent the current free memory space of the vector container;
  • _ Myfirst and_ Myend can be used to represent the capacity of the vector container.

For an empty vector container, there is no space allocation for any element, so_ Myfirst,_ Mylast and_ Myend is null.

By flexibly using these three iterators, the vector container can easily realize almost all functions such as head and tail identification, size, container and empty container judgment, such as:

template <class _Ty, class _Alloc = allocator<_Ty>>
class vector{
public: 
    iterator begin() {return _Myfirst;}
    iterator end() {return _Mylast;}
    size_type size() const {return size_type(end() - begin());}
    size_type capacity() const {return size_type(_Myend - begin());}
    bool empty() const {return begin() == end();}
    reference operator[] (size_type n) {return *(begin() + n);}
    reference front() { return *begin();}
    reference back() {return *(end()-1);}
    ...
};

The essence of vector expanding capacity

In addition, it should be noted that when the size and capacity of the vector are equal (size==capacity), that is, when it is fully loaded, if you add elements to it, the vector needs to be expanded. The expansion process of vector container needs to go through the following three steps:

  1. Completely discard the existing memory space and re apply for more memory space;
  2. Move the data in the old memory space to the new memory space in the original order;
  3. Finally, free up the old memory space.

This explains why the pointers, references and iterators associated with the vector container may fail after it is expanded.

It can be seen that vector expansion is very time-consuming. In order to reduce the cost of reallocating memory space, vector will apply for more memory space than the user needs each time it is expanded (that is, the origin of vector capacity, i.e. capacity > = size) for later use.

When the vector container is expanded, the amount of more memory space requested by different compilers is different. Take VS as an example, it will expand the capacity of the existing container by 50%.

Detailed explanation of adding elements (push_back() and replace_back()) to C++ STL vector

Instance 16 (push_back() function):

/*******************************************************************
 *   > File Name: stl-vector-push_back.cpp
 *   > Create Time: 2021 October 16, 2013 23:49:05
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>values{};
    values.push_back(10);//Add element at tail
    values.push_back(100);//Add element at tail

    for(int i = 0; i< values.size(); i++){
        cout << values[i] << " ";
    }
    cout << endl;

    return 0;
}

function:

PS D:\study\cplusplus\day16> .\stl-vector-push_back.exe
10 100

Instance 17 (replace_back() function)

#include <iostream>
#include <vector>

using namespace std;
int main(){    
    vector<int> values{};
    
    values.emplace_back(1);//Add element at tail    
    values.emplace_back(2);//Add element at tail    
    for (int i = 0; i < values.size(); i++) {        
        cout << values[i] << " ";    
    }    
    
    return 0;
}

function:

1 2

emplace_back() and push_ The difference between back()

emplace_back() and push_ The difference of back () lies in the different mechanisms of the underlying implementation. push_ When back() adds an element to the tail of the container, it will first create the element, and then copy or move the element to the container (if it is copied, the previously created element will be destroyed later); And empty_ When back () is implemented, it creates this element directly at the end of the container, eliminating the process of copying or moving elements.

Example 18

/*******************************************************************
 *   > File Name: emplace_back.cpp
 *   > Create Time: 2021 October 19, 2014 23:41:15
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

class testDemo{
public:
    testDemo(int num):num(num){
        std::cout << "Constructor" << endl;
    }

    testDemo(const testDemo& other):num(other.num){
        std::cout << "Call copy constructor" << endl;
    }
    testDemo(testDemo&& other):num(other.num){
        std::cout << "Call the move constructor" << endl;
    }
    ~testDemo(){
        std::cout << "Destructor" << endl;
    }
private:
    int num;
};

int main(int argc, char* argv[])
{
    cout << "emplace_back:" << endl;
    std::vector<testDemo>demo1;
    demo1.emplace_back(2);

    cout << "push_back:" << endl;
    std::vector<testDemo>demo2;
    demo2.push_back(2);

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day17> make
g++ -o emplace_back emplace_back.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day17> .\emplace_back.exe
emplace_back:
Constructor
push_back:
Constructor
 Call the move constructor
 Destructor
 Destructor
 Destructor

Example 19

/*******************************************************************
 *   > File Name: emplace_back.cpp
 *   > Create Time: 2021 October 19, 2014 23:41:15
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

class testDemo{
public:
    testDemo(int num):num(num){
        std::cout << "Constructor" << endl;
    }

    testDemo(const testDemo& other):num(other.num){
        std::cout << "Call copy constructor" << endl;
    }
    // testDemo(testDemo&& other):num(other.num){
        // STD:: cout < < call mobile constructor < < endl;
    // }
    ~testDemo(){
        std::cout << "Destructor" << endl;
    }
private:
    int num;
};

int main(int argc, char* argv[])
{
    cout << "emplace_back:" << endl;
    std::vector<testDemo>demo1;
    demo1.emplace_back(2);

    cout << "push_back:" << endl;
    std::vector<testDemo>demo2;
    demo2.push_back(2);

    return 0;
}

Compile and run:

PS E:\fly-prj\cplusplus\day33> make 
g++ -o emplace_back emplace_back.cpp -g -Wall -std=c++11
PS E:\fly-prj\cplusplus\day33> .\emplace_back.exe
emplace_back:
Constructor
push_back:
Constructor
 Call copy constructor
 Destructor
 Destructor
 Destructor

As can be seen from examples 18 and 19, push_ When back() is implemented at the bottom level, it will call the move constructor first. If not, it will call the copy constructor.

Obviously, do the same thing, push_ The underlying implementation process of back() is better than that of empty()_ Back () is more cumbersome, in other words, empty_ Back() is more efficient than push()_ Back () high. Therefore, in actual use, it is recommended that you give priority to use empty_ back().

Because empty_ Back() is a new addition to the C++ 11 standard. If the program needs to take into account the previous version, it should still use push_back().

C++ STL vector insert elements (insert() and replace()) details

The vector container provides two member functions, insert() and replace (), which are used to insert elements at the specified location of the container.

insert()

The function of the insert() function is to insert one or more elements at the specified position of the vector container.

Syntax formatUsage instructions
iterator insert(pos,elem)Inserts a new element element before the position specified by the iterator pos, and returns the iterator representing the position of the newly inserted element.
iterator insert(pos,n,elem)Insert n element elements before the position specified by iterator pos, and return the iterator representing the position of the first newly inserted element.
iterator insert(pos,first,last)Insert all elements in the [first,last] area of other containers (not limited to vector s) before the position specified by the iterator pos, and return the iterator representing the position of the first newly inserted element.
iterator insert(pos,initlist)Insert all elements in the initialization list (multiple elements enclosed in braces {} separated by commas) before the position specified by the iterator pos, and return the iterator representing the position of the first newly inserted element.

Instance 20 (insert())

/*******************************************************************
 *   > File Name: stl-vector-insert.cpp
 *   > Create Time: 2021 22:32:33, October 22
 ******************************************************************/
#include <iostream>
#include <vector>
#include <array>
using namespace std;

template <typename T>
void printVector(vector<T> vec){
    for(auto&& value:vec){
        cout << value << " ";
    }
    cout << endl;
}

int main(int argc, char* argv[])
{
    vector<int>values {1,2};
    printVector(values);

    values.insert(values.begin() + 1, 3);
    printVector(values);

    values.insert(values.end(), 2, 5);
    printVector(values);

    std::array<int, 3>test{ 7, 8, 9};
    values.insert(values.end(), test.begin(), test.end());
    printVector(values);

    values.insert(values.end(), {10, 11});
    printVector(values);

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day17> make stl-vector-insert
g++ -o stl-vector-insert stl-vector-insert.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day17> .\stl-vector-insert.exe
1 2
1 3 2
1 3 2 5 5
1 3 2 5 5 7 8 9
1 3 2 5 5 7 8 9 10 11

emplace()

Empty() yes C++ The newly added member function of the 11 standard is used to insert a new element (only one element can be inserted) before the specified position of the vector container.

iterator emplace (const_iterator pos, args...);

Where pos is the iterator that specifies the insertion position; args... Indicates multiple parameters corresponding to the constructor of the newly inserted element; This function returns an iterator that represents the location of the newly inserted element.

Instance 21 (empty() member function)

/*******************************************************************
 *   > File Name: stl-vector-emplace.cpp
 *   > Create Time: 2021 October 24, 2013 21:50:42
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    std::vector<int> demo1{1,2};
    demo1.emplace(demo1.begin(), 3);
    for(int i = 0; i< demo1.size() ; i++){
        cout << demo1[i] << " ";
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day17> make stl-vector-emplace
g++ -o stl-vector-emplace stl-vector-emplace.cpp -g -Wall -std=c++11
stl-vector-emplace.cpp: In function'int main(int, char**)'in:
stl-vector-emplace.cpp:16:21: Warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>:
:size_type' {aka 'long unsigned int'} [-Wsign-compare]
   16 |     for(int i = 0; i< demo1.size() ; i++){
      |                    ~^~~~~~~~~~~~~~
PS D:\study\cplusplus\day17> ./stl-vector-emplace.exe
3 1 2

Instance 22 (insert() and empty() functions)

/*******************************************************************
 *   > File Name: stl-vector-emplace1.cpp
 *   > Create Time: 2021 21:58:16, October 24
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

class testDemo{
public:
    testDemo(int num):num(num){
        std::cout << "Call constructor" << endl;
    }
    testDemo(const testDemo& other):num(other.num){
        std::cout << "Call copy constructor" << endl;
    }
    testDemo(testDemo&& other):num(other.num){
        std::cout << "Call the move constructor" << endl;
    }
    testDemo& operator=(const testDemo& other);
private:
    int num;
};

testDemo& testDemo::operator=(const testDemo& other){
    this->num = other.num;
    return *this;
}

int main(int argc, char* argv[])
{
    cout << "Insert:" << endl;
    std::vector<testDemo> demo2{};
    demo2.insert(demo2.begin(), testDemo(1));

    cout << "emplace: " << endl;
    std::vector<testDemo> demo1{};
    demo1.emplace(demo1.begin(), 1);
    
    return 0;
}

Compile and run:

PS D:\study\cplusplus\day17> make stl-vector-emplace1
g++ -o stl-vector-emplace1 stl-vector-emplace1.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day17> .\stl-vector-emplace1.exe
Insert:
Call constructor
 Call the move constructor
emplace:
Call constructor

Note that when the copy constructor and the move constructor exist at the same time, insert() will call the move constructor first.

Both empty () and insert() can insert new elements into the vector container. It can be seen from the above program that empty () is more efficient than insert(). When inserting an element, replace () constructs the element directly at the specified location of the container, rather than generating it separately and then copying (or moving) it to the container.

Several ways of deleting elements in C++ STL vector (super detailed)

There are several ways to delete vector container elements:

functionfunction
pop_back()Delete the last element in the vector container. The size of the container will be reduced by 1, but the capacity will not change.
erase(pos)Deletes the element at the position specified by the pos iterator in the vector container and returns the iterator pointing to the element at the next position of the deleted element. The size of the container will be reduced by 1, but the capacity will not change.
swap(beg),pop_back()First call the swap() function to exchange the location of the target element to be deleted and the last element of the container, and then use pop_back() deletes the target element.
erase(beg,end)Deletes all elements within the area specified by the iterator [beg,end) in the vector container, and returns the iterator pointing to the next element in the deleted area. The size of the container will be reduced, but the capacity will not be changed.
remove()Deletes all elements in the container equal to the specified element value and returns an iterator pointing to the next position of the last element. It is worth mentioning that calling this function will not change the size and capacity of the container.
clear()Delete all elements in the vector container and make it an empty vector container. This function changes the size of the vector (to 0), but not its capacity.

Instance 23 (pop_back() function)

/*******************************************************************
 *   > File Name: vector-pop_back.cpp
 *   > Create Time: 2021 November 1, 2003 23:51:03
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>demo{1, 2, 3, 4, 5};
    demo.pop_back(); /*Delete last element*/

    cout << "size is :" << demo.size() << endl; /*Size of output container*/
    cout << "capacity is :" << demo.capacity() << endl; /*Output container capacity*/

    for(int i=0; i< demo.size(); i++){
        cout << demo[i] << " "; /*Traverses the elements in the output container*/
    }
    cout << endl;

    return 0;
}

Compile and run:

PS D:\study\cplusplus\day18> make
g++ -o vector-pop_back vector-pop_back.cpp -g -Wall -std=c++11
PS D:\study\cplusplus\day18> .\vector-pop_back.exe
size is :4
capacity is :5
1 2 3 4

Instance 24 (erase() function)

/*******************************************************************
 *   > File Name: vector-erase.cpp
 *   > Create Time: 2021 November 1, 2013 23:56:50
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>demo {1, 2, 3, 4, 5};
    auto iter = demo.erase(demo.begin() + 1);

    cout << "size is :" << demo.size() << endl;
    cout << "capacity is :" << demo.capacity() << endl;

    for(int i=0; i< demo.size(); i++){
        cout << demo[i] << " ";
    }
    cout << endl << *iter << endl;

    return 0;
}

Operation results:

PS D:\study\cplusplus\day18> .\vector-erase.exe
size is :4
capacity is :5
1 3 4 5
3

Instance 25 (swap() and pop_back() functions)

/*******************************************************************
 *   > File Name: vector-swap.cpp
 *   > Create Time: 2021 22:08:06, November 2
 ******************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(int argc, char* argv[])
{
    vector<int>demo{1,2,3,4,5};
    swap(*(std::begin(demo)+1), *(std::end(demo)-1));/*Exchange element*/

    for(int i = 0; i< demo.size(); i++){
        cout << demo[i] << " ";
    }
    cout << endl;

    demo.pop_back();/*Remove the last element of the container*/

    cout << "size is : " << demo.size() << endl;
    cout << "capacity is : " << demo.capacity() << endl;

    for(int i = 0; i< demo.size(); i++){
        cout << demo[i] << " ";
    }
    cout << endl;

    return 0;
}

function:

PS D:\study\cplusplus\day18> .\vector-swap.exe
1 5 3 4 2
size is : 4
capacity is : 5
1 5 3 4

Instance 26 (erase(begin, end) function)

/*******************************************************************
 *   > File Name: vector-erase1.cpp
 *   > Create Time: 2021 22:19:16, November 2
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
    std::vector<int>demo{1, 2, 3, 4, 5, 6};
    //Delete 2,3,4
    auto iter = demo.erase(demo.begin()+1, demo.end()-3);
    cout << "*iter is : " << *iter << endl;
    cout << "size is :" << demo.size() << endl;
    cout << "capacity is : " << demo.capacity() << endl;

    for(int i = 0; i< demo.size(); i++){
        cout << demo[i] << " ";
    }
    cout << endl;

    return 0;
}

function:

PS D:\study\cplusplus\day18> .\vector-erase1.exe
*iter is : 4
size is :4
capacity is : 6
1 4 5 6

Instance 27 (remove() function)

/*******************************************************************
 *   > File Name: stl-vector-remove.cpp
 *   > Create Time: 2021 November 7, 2009 9:21:01
 ******************************************************************/

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(void)
{
    std::vector<int>demo{1, 3, 3, 4, 3, 5};
    auto iter = std::remove(demo.begin(), demo.end() , 3);

    cout << "iter is : " << *iter << endl;
    cout << "size is : " << demo.size() << endl;
    cout << "capacity is : " << demo.capacity() << endl;

    for(auto first = demo.begin(); first < iter ; ++ first){
        cout << *first << " ";
    }
    cout << endl;

    for(int i = 0; i < demo.capacity(); i++){
        cout << demo[i] << " ";
    }
    cout << endl;
    
    return 0;
}

function:

PS E:\MyStudy\cplusplus\day1> .\stl-vector-remove.exe
iter is : 4
size is : 6
capacity is : 6
1 4 5
1 4 5 4 3 5

remove() The implementation principle of is that when traversing the elements in the container, once the target element is encountered, mark it, and then continue traversing until a non target element is found, that is, use this element to cover the first marked position. At the same time, mark the position of the non target element, and wait for a new non target element to cover it. Therefore, if the above program All the elements of the demo container in are output, and the result is 1 4 5 4 3 5.

Instance 28 (remove() function)

The operation of example 27 shows that the remove function deletes multiple specified elements in the demo, the size and capacity of the container remain unchanged, and the previously stored elements are retained in the remaining positions. These elements can be deleted by using the erase function.

/*******************************************************************
 *   > File Name: stl-vector-remove1.cpp
 *   > Create Time: 2021 November 7, 2009 9:49:43
 ******************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(void)
{
    vector<int>demo{1, 3, 3, 4, 3, 5};
    auto iter = std::remove(demo.begin(), demo.end(), 3);
    demo.erase(iter, demo.end());
    cout << "size is : " << demo.size() << endl;
    cout << "capacity is : " << demo.capacity() << endl;

    for(int i = 0; i < demo.size() ; i++){
        cout << demo[i] << " " ;
    } 
    cout << endl;

    return 0;
}

Compile and run:

PS E:\MyStudy\cplusplus\day1> .\stl-vector-remove1.exe
size is : 3
capacity is : 6
1 4 5

Instance 29 (clear() function)

/*******************************************************************
 *   > File Name: stl-vector.clear.cpp
 *   > Create Time: 2021 November 7, 2010 10:01:06
 ******************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(void)
{
    vector<int>demo{1, 3, 3, 4, 3, 5};
    demo.clear();

    cout << "size is : " << demo.size() << endl;
    cout << "capacity is : " << demo.capacity() << endl;

    return 0;
}

Compile and run:

PS E:\MyStudy\cplusplus\day1> .\stl-vector_clear.exe
size is : 0
capacity is : 6

How to avoid unnecessary expansion of the vector container?

The whole process of vector container expansion is similar to the implementation method of realloc() function, which is roughly divided into the following four steps:

  1. Allocate a new storage space several times the size of the current vector. Note that in most STL versions, the vector container will grow by a multiple of 2, that is, each time the vector container expands, its capacity will increase to twice the previous capacity;

  2. Copy all elements stored in the vector container from the old storage space to the new storage space according to the original order;

  3. Destruct all elements stored in the old storage space;

  4. Free up old storage space.

The expansion process of the vector container is very time-consuming, and when the container is expanded, all previous pointers, iterators and references related to the container will become invalid. Therefore, we should try to avoid unnecessary capacity expansion when using the vector container.

Member methods with similar functions in the vector template class:

Member methodfunction
size()Tell us how many elements exist in the current vector container, but only through this method, we can't know how much storage space the vector container has.
capacity()Tell us how many elements the current vector container can hold in total. If you want to know how much unused storage space the current vector container has, you can know through capacity()-size(). Note that if the values returned by size () and capacity() are the same, there is no available storage space in the current vector container, which means that adding a new element to the vector container next time will cause the vector container to expand.
resize(n)Force the vector container to store n elements. Note that if n is smaller than the return value of size(), the extra elements at the end of the container will be destructed (deleted); If n is larger than size(), vector will create more default value elements with the help of the default constructor and store them at the end of the container; If n is larger than the return value of capacity(), the vector will be expanded first and some default value elements will be added.
reserve(n)Force the capacity of the vector container to be at least n. Note that if n is smaller than the capacity of the current vector container, the method will do nothing; Conversely, if n is larger than the capacity of the current vector container, the vector container will expand.

**Summary: * * as long as there are new elements to be added to the vector container, and the capacity of the vector container is insufficient at this time, the container will be expanded automatically.

Therefore, the key to avoid unnecessary capacity expansion of the vector container is to set its capacity to a large enough value at the initial stage of using the vector container. In other words, the moment the vector container is constructed, it should be expanded to a large enough capacity with the help of the reserve() member method.

Example 30

Suppose we want to create a vector < int > containing 1 ~ 1000, which is usually implemented as follows:

vector<int>myvector;
for (int i = 1; i <= 1000; i++) {
    myvector.push_back(i);
}

During the whole cycle of the above code, the vector container will be automatically expanded 2 ~ 10 times (in most STL standard library versions, the vector container will usually be expanded to twice the current capacity, and here 1000 ≈ 2 ^ 10). The execution efficiency of the program can be imagined.

Example 31

Use the reserve() method to avoid unnecessary capacity expansion of the vector container.

vector<int>myvector;
myvector.reserve(1000);
cout << myvector.capacity();
for (int i = 1; i <= 1000; i++) {
    myvector.push_back(i);
}

Compared with the previous code implementation, the capacity of the vector container is only expanded once during the operation of the whole program, and the execution efficiency is greatly improved.

Of course, in the actual scenario, we may not know how many elements the vector container needs to store. In this case, enough space can be reserved first, and then the excess capacity can be removed after all elements are stored in the vector container.

For how to remove the excess capacity of the vector container, you can use the shrink provided by the container template class_ to_ Fit() member method.

The vector swap() member method can also be used like this!

Example 32

In the process of using the vector container, its container will expand itself as needed. For example, use push_ When member methods such as back (), insert(), empty () add new elements to the vector container, if the current container is full (that is, size() == capacity()), it will expand its capacity to meet the needs of adding new elements. Of course, you can also call the reserve() member method to manually increase the capacity of the current vector container.

/*******************************************************************
 *   > File Name: stl-myvector.cpp
 *   > Create Time: 2021 November 7, 2011 11:17:40
 ******************************************************************/
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
    vector<int> myvector;
    cout << "1.myvector size is " << myvector.size() << " , ";
    cout << "capacity is " << myvector.capacity() << endl;

    for(int i = 1; i <= 10; i++){
        myvector.push_back(i);
    }

    cout << "2.myvector size is " << myvector.size() << " , ";
    cout << "capacity is " << myvector.capacity() << endl;

    myvector.reserve(1000);

    cout << "3.myvector size is " << myvector.size() << " , ";
    cout << "capacity is " << myvector.capacity() << endl;

    return 0;
}

function:

g++ -o stl-vector_clear stl-vector_clear.cpp -g -Wall -std=c++11
PS E:\MyStudy\cplusplus\day1> .\stl-myvector.exe
1.myvector size is 0 , capacity is 0
2.myvector size is 10 , capacity is 16
3.myvector size is 10 , capacity is 1000

Tags: C++ Operation & Maintenance Container

Posted on Thu, 11 Nov 2021 14:09:39 -0500 by jasper182