STL Vector

Vector

Structure of a Vector
需要包含头文件<vector>
定义:

1
2
3
4
5
namespace std {
template < typename T,
typename Allocator = allocator<T> >
class vector;
}

顺序容器。提供随机存取,可在常量时间内通过下标存取任何元素。迭代器是random-access iterator,所以可以使用STL里的所有算法函数。
在vector的末尾添加或删除元素效率很高。如果在开头或中间删除或插入元素,效率比较低。

Vector容器的操作

Create, Copy and Destroy

Operation Effect
vector c Default constructor; creates an empty vector without any elements
vector c(c2) Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector c = c2 Copy constructor; creates a new vector as a copy of c2 (all elements are copied)
vector c(rv) Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)
vector c = rv Move constructor; creates a new vector, taking the contents of the rvalue rv (since C++11)
vector c(n) Creates a vector with n elements created by the default constructor
vector c(n, elem) Creates a vector initialized with n copies of element elem
vector c(beg, end) Creates a vector initialized with the elements of the range [beg, end)
vector c(initlist) Creates a vector initialized with the elements of initializer list initlist (since C++11)
vector c = initlist Creates a vector initialized with the elements of initializer list initlist (since C++11)
c.~vector() Destroys all elements and frees the memory

Nonmodifying Operations

Operation Effect
c.empty() Returns whether the container is empty (equivalent to size()==0 but might be faster)
c.size() Returns the current number of elements
c.max_size() Returns the maximum number of elements possible
c.capacity() Returns the maximum possible number of elements without reallocation
c.reserve(num) Enlarges capacity, if not enough yet
c.shrink_to_fit() Request to reduce capacity to fit number of elements (since C++11)
c1 == c2 Returns whether c1 is equal to c2 (calls == for the elements)
c1 != c2 Returns whether c1 is not equal to c2 (equivalent to !(c1==c2) )
c1 < c2 Returns whether c1 is less than c2
c1 > c2 Returns whether c1 is greater than c2 (equivalent to c2<c1)
c1 <= c2 Returns whether c1 is less than or equal to c2 (equivalent to!(c2<c1) )
c1 >= c2 Returns whether c1 is greater than or equal to c2 (equivalent to !(c1<c2) )

Assignments

Operation Effect
c = c2 Assigns all elements of c2 to c
c = rv Move assigns all elements of the rvalue rv to c (since C++11)
c = initlist Assigns all elements of the initializer list initlist to c (since C++11)
c.assign(n, elem) Assigns n copies of element elem
c.assign(beg, end) Assigns the elements of the range [beg,end)
c.assign(initlist) Assigns all the elements of the initializer list initlist
c1.swap(c2) Swaps the data of c1 and c2
swap(c1, c2) Swaps the data of c1 and c2

Element Access

Operation Effect
c[idx] Returns the element with index idx (no range checking)
c.at(idx) Returns the element with index idx (throws range-error exception if idx is out of range)
c.front() Returns the first element (no check whether a first element exists)
c.back() Returns the last element (no check whether a last element exists)

Iterator Functions

random-access iterator。所以可以用STL里的所有Algorithms。

Operation Effect
c.begin() Returns a random-access iterator for the first element
c.end() Returns a random-access iterator for the position after the last element
c.cbegin() Returns a constant random-access iterator for the first element (since C++11)
c.cend() Returns a constant random-access iterator for the position after the last element (since C++11)
c.rbegin() Returns a reverse iterator for the first element of a reverse iteration
c.rend() Returns a reverse iterator for the position after the last element of a reverse iteration
c.crbegin() Returns a constant reverse iterator for the first element of a reverse iteration (since C++11)
c.crend() Returns a constant reverse iterator for the position after the last element of a reverse iteration (since C++11)

Inserting and Removing Elements

Operation Effect
c.push_back(elem) Appends a copy of elem at the end
c.pop_back() Removes the last element (does not return it)
c.insert(pos, elem) Inserts a copy of elem before iterator position pos and returns the position of the new element
c.insert(pos, n, elem) Inserts n copies of elem before iterator position pos and returns the position of the first new element (or pos if there is no new element)
c.insert(pos, beg, end) Inserts a copy of all elements of the range [beg,end) before iterator position pos and returns the position of the first new element (or pos if there is no new element)
c.insert(pos, initlist) Inserts a copy of all elements of the initializer list initlist before iterator position pos and returns the position of the first new element (or pos if there is no new element; since C++11)
c.emplace(pos, args…) Inserts a copy of an element initialized with args before iterator position pos and returns the position of the new element (since C++11)
c.emplace_back(args…) Appends a copy of an element initialized with args at the end (returns nothing; since C++11)
c.erase(pos) Removes the element at iterator position pos and returns the position of the next element
c.erase(beg, end) Removes all elements of the range [beg,end) and returns the position of the next element
c.resize(num) Changes the number of elements to num (if size() grows new elements are created by their default constructor)
c.resize(num, elem) Changes the number of elements to num (if size() grows new elements are copies of elem)
c.clear() Removes all elements (empties the container)

效率比较高的做法:

  • 在vector末尾删除或添加元素。
  • 初始化时就预留好足够空间。
  • 多个元素一次性插入,而不是一个一个。

使用Vector的示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Examples of Using Vector
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{

// create empty vector for strings
vector<string> sentence;
//reserve memory for five elements to avoid reallocation
sentence.reserve(5);
// append some elements
sentence.push_back("Hello,");
vector<string> temp;
temp.push_back("how");
temp.push_back("are");
temp.push_back("you");
temp.push_back("?");
sentence.insert(sentence.end(), temp.begin(), temp.end());
//sentence.insert(sentence.end(), {"how", "are", "you", "?"});
// print elements separated with spaces
copy(sentence.cbegin(), sentence.cend(), ostream_iterator<string>(cout, " "));
cout<<endl;
// print "technical data"
cout<<"max_size(): "<<sentence.max_size()<<endl;
cout<<"size(): "<<sentence.size()<<endl;
cout<<"capacity(): "<<sentence.capacity()<<endl;
// swap second and fourth element
swap(sentence[1], sentence[3]);
// insert element "always" before element "?"
sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always");
//assign "!" to the last element
sentence.back() = "!";
// print elements separated with spaces
copy(sentence.cbegin(), sentence.cend(), ostream_iterator<string>(cout, " "));
cout<<endl;
// print some "technical data" again
cout<<"size(): "<<sentence.size()<<endl;
cout<<"capacity(): "<<sentence.capacity()<<endl;
// delete last two elements
sentence.pop_back();
sentence.pop_back();
// shrink capacity (since C++11)
sentence.shrink_to_fit();
// print some "technical data" again
cout<<"size(): "<<sentence.size()<<endl;
cout<<"capacity(): "<<sentence.capacity()<<endl;
system("Pause");
}

[1] The C++ Standard Library 2nd Edition