C++ Vector usage

  • 2020-04-02 03:07:36
  • OfStack

Vector is part of the C++ Standard Template Library. The reason why it is considered as a container is that it can store various types of objects like a container. To put it simply, vector is a dynamic array that can store arbitrary types and can increase and compress data.

You must add a vector container before using it < The vector > Header: #include < The vector > ;

Vector belongs to the contents of the STD naming domain, so it needs to be qualified by using STD ::vector; You can also use the global namespace approach directly: using namespace STD;

Vector member function

C. push_back(elem) inserts an elem data in the tail.


vector<int> v;
    v.push_back(1);

C.pop_back () deletes the data at the end.

vector<int> v;
    v.pop_back();

C. beg (end) assigns data from an open interval [beg,end] to c.


vector<int> v1,v2;
v1.push_back(10);
v1.push_back(20);
v2.push_back(30);
v2.assign(v1.begin(),v1.end());

C.assign (n,elem) assigns n copies of elem to c.


vector<int> v;
v.assign(5,10);//Put five tens in v

C.a t(int index) returns the index data. If the index is out of bounds, an out_of_range exception is thrown.


vecto<int> v;
cout << v.at(2) << endl;// print vector The subscript is 2 The data of 

C. begin() returns an iterator that points to the first data.

C.nd () returns an iterator that points to the last data.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::iterator it;
for(it = v.begin();it!=v.end();it++){
  cout << *it << "t";
}
cout << endl;

C. begin() returns the first data in the reverse queue, the last data in the c container.

C.end () returns the next position of the last data in the reverse queue, that is, the first data in the c container before that.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::reverse_iterator it;
for(it = v.rbegin();it!=v.rend();it++){
 cout << *it << "t";
}
cout << endl;

C. apacity() returns the number of data in the container, doubling.


vector<int> v;
v.push_back(1);
cout << v.capacity() << endl; // 1
v.push_back(2);
cout << v.capacity() << endl; // 2
v.push_back(3);
cout << v.capacity() << endl; // 4

C. Lear () removes all data in the container.


vector<int>::iterator it;
for(it = v.begin();it!=v.end();it++){
 cout << *it << "t";
}
v.clear();
for(it = v.begin();it!=v.end();it++){
 cout << *it << "t";
}
cout << endl;

C.mpty () determines if the container is empty.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
if(!v.empty()){
 cout << "v is not empty!" << endl;  
}

C.ase (pos) deletes data from the pos location and returns the location of the next data.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.erase(v.begin());

C.ase (beg,end) deletes data from the [beg,end) interval and returns the location of the next data.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.erase(v.begin(),v.end());

C.front () returns the first data.

C.ack () returns the last data without checking for its existence.


vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
if(!vec.empty()){
    cout << " the first number is: " << v.front() << endl;
    cout << " the last number is: " << v.back() << endl;
}

C.issert (pos,elem) inserts a copy of elem at the pos position, returning the iterator of the inserted value.

C.i. Nsert (pos,n,elem) inserts n elem data at the pos position, with no return value.

C.i. Nsert (pos,beg,end) inserts data in the interval [beg,end) at the pos position, with no return value.


vector<int> v;
v.insert(v.begin(),10);
v.insert(v.begin(),2,20);
v.insert(v.begin(),v1.begin(),v1.begin()+2);

C.ize () returns the number of actual data in the container.

C.ruesize (num) respecifies the length of the queue. Often used to increase the length of a vector, small - > Big ok... > Small useless!)

C. eserve() reserve appropriate capacity.

A little analysis for resize() and reserver() :

Reserve is a container that reserves space, but does not actually create an element object. You cannot refer to an element in the container before creating the object, so you need to use the push_back()/insert() function when adding a new element.

Resize is to change the size of the container and create the object, so after calling this function, you can refer to the object inside the container, so when adding a new element, use the operator[] operator or iterator to refer to the element object.

Furthermore, the forms of the two functions are different. After the reserve function, there is an argument, that is, the space of the container that needs to be reserved. The resize function can take two arguments, the first to the new size of the container, the second to add a new element in the container, and if this argument is omitted, the default constructor of the element object is called.

  Reserve simply guarantees that the vector's capacity is at least as large as its parameter n. In the range of [0, n), if the index is subscript, the access of vector[index] may be legal or illegal, depending on the specific situation.
        What resize and reserve interfaces have in common is that they both guarantee that the vector's capacity is at least as large as its parameters specify.

C.ax_size () returns the maximum amount the container can hold.

C1. Swap (c2) swaps c1 and c2.

Swap (c1, c2).


vector<int> v1,v2,v3;
v1.push_back(10);
v2.swap(v1);
swap(v3,v1);

The vector < The type > C; Create an empty vector container.

The vector < The type > C1 (c2); Copy a vector.

The vector < The type > C (n); Create a vector with n data, all of which are generated by default, that is, all 0;

The vector < The type > C (n,elem) creates a vector with n copies of elem data.

The vector < The type > C (beg,end) creates a vector with an interval of [beg,end).

~ the vector < The type > (a)     Destroy all data and cast memory.

Compress a bloated vector

Many times a large amount of data is deleted, or through the use of reserver(), the resulting vector is much larger than it needs to be. So you need to compress the vector to its actual size. Resize () increases the size of the vector. Clear () simply removes the data in the container and does not change the size of capacity(), so it is important to compress the vector.

Test the clear() function:


//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//& have spent Copyright (c) 2013 sam. All rights reserved.
// #include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{     // insert code here...
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    vector<int>::iterator it;
    cout << "clear before:" << " ";
    for(it=v.begin();it!=v.end();it++){
        cout << *it << "t";
    }
    cout << endl;
    cout << "clear before capacity:" << v.capacity() << endl;
    v.clear();
    cout << "after clear:" << " ";
    for(it=v.begin();it!=v.end();it++){
        cout << *it << "t";
    }
    cout << endl;
    cout << "after clear capacity:" << v.capacity() << endl;
    return 0;
}

Results:


clear before: 1    2    3   
clear before capacity:4
after clear:
after clear capacity:4

Why the output of capacity() printed here is 4 is not explained in detail, please refer to the introduction of capacity above. As a result, we can see that the data is all cleared after clear(), but capacity() is still 4.

Suppose: we create a new vector from the original vector. Let's see what happens.


//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//& have spent Copyright (c) 2013 sam. All rights reserved.
// #include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{     // insert code here...
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << "v.capacity()" << v.capacity() << endl;
   
    vector<int> v1(v);
    cout << "v1.capacity()" << v1.capacity() << endl;
    return 0;
}

Results:


v.capacity()4
v1.capacity()3

It can be seen that v1's capacity() is the actual size of v, so the vector can be compressed. But we don't want to create a new one, we want to compress on the original vector, so think about it in another way.

Suppose we swap v1 back to v using the swap function, and see what happens.


//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//& have spent Copyright (c) 2013 sam. All rights reserved.
// #include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{     // insert code here...
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << "v.capacity()" << v.capacity() << endl;
   
    vector<int> v1(v);
    cout << "v1.capacity()" << v1.capacity() << endl;
   
    v.swap(v1);
    cout << "v.swap(v1).capacity()" << v.capacity() << endl;
    return 0;
}

Results:


v.capacity()4
v1.capacity()3
v.swap(v1).capacity()3

As you can see, v.apacity () becomes 3, and that's it. However, the code felt cumbersome, we reconsidered a new writing method, using anonymous object to replace the intermediate object v1: vector < int > (v). Swap (v);

Testing:


//
//  vector.cpp
//  vector
//
//  Created by scandy_yuan on 13-1-7.
//& have spent Copyright (c) 2013 sam. All rights reserved.
// #include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{     // insert code here...
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    cout << "v.capacity()" << v.capacity() << endl;
   
    vector<int> (v).swap(v);
    cout << "v.capacity()" << v.capacity() << endl;
    return 0;
}

Results:


v.capacity()4
v.capacity()3

You can see that v.apacity () is programmed by 4 to achieve 3.

Instead of focusing on C++ 11, thanks to @egmkang, it does provide shrink_to_fit () in C++ 11 to compress the vector.

As follows:


#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v;
    std::cout << "Default-constructed capacity is " << v.capacity() << 'n';
    v.resize(100);
    std::cout << "Capacity of a 100-element vector is " << v.capacity() << 'n';
    v.clear();
    std::cout << "Capacity after clear() is " << v.capacity() << 'n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << 'n';
}

Results:


Default-constructed capacity is 0
Capacity of a 100-element vector is 100
Capacity after clear() is 100
Capacity after shrink_to_fit() is 0


Related articles: