std::vector

文章详细介绍了C++标准库中的vector容器,包括其作为动态数组的特性、性能优势、如何通过位置索引访问元素、添加和删除元素、与其他序列容器(deque和list)的比较,以及容量、大小、迭代器等相关操作。文章还提到了vector的内存管理和自动扩展功能,以及如何通过resize和reserve等方法控制容量和大小。
摘要由CSDN通过智能技术生成
Vector

Vectors are a kind of sequence containers. As such, their elements are ordered following a strict linear sequence.
向量是一种序列容器。因此,它们的元素是按照严格的线性序列排列的。

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.
矢量容器被实现为动态数组;与常规数组一样,向量容器的元素存储在连续的存储位置,这意味着它们的元素不仅可以使用迭代器访问,还可以使用指向元素的常规指针的偏移量访问。

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.
但与常规阵列不同,矢量中的存储是自动处理的,可以根据需要进行扩展和收缩。

Vectors are good at:

Accessing individual elements by their position index (constant time). 
通过位置索引(恒定时间)访问各个元素。
Iterating over the elements in any order (linear time). 
以任何顺序(线性时间)在元素上迭代。
Add and remove elements from its end (constant amortized time). 
从其末尾添加和删除元素(固定摊销时间)。
Compared to arrays, they provide almost the same performance for these tasks, plus they have the ability to be easily resized. Although, they usually consume more memory than arrays when their capacity is handled automatically (this is in order to accomodate for extra storage space for future growth).
与阵列相比,它们为这些任务提供了几乎相同的性能,而且还可以轻松调整大小。尽管如此,当它们的容量被自动处理时,它们通常比阵列消耗更多的内存(这是为了适应未来增长的额外存储空间)。

Compared to the other base standard sequence containers (deques and lists), vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence. For operations that involve inserting or removing elements at positions other than the end, they perform worse than deques and lists, and have less consistent iterators and references than lists.
与其他基本标准序列容器(deques和list)相比,向量通常在访问元素以及在序列末尾添加或删除元素的时间上最有效。对于在末尾以外的位置插入或删除元素的操作,它们的性能比deques和list差,迭代器和引用的一致性也不如list。

Internally, vectors -like all containers- have a size, which represents the amount of elements contained in the vector. But vectors, also have a capacity, which determines the amount of storage space they have allocated, and which can be either equal or greater than the actual size. The extra amount of storage allocated is not used, but is reserved for the vector to be used in the case it grows. This way, the vector does not have to reallocate storage on each occasion it grows, but only when this extra space is exhausted and a new element is inserted (which should only happen in logarithmic frequence in relation with its size).
在内部,向量和所有容器一样,都有一个大小,表示向量中包含的元素数量。但是向量也有一个容量,它决定了它们分配的存储空间量,并且可以等于或大于实际大小。分配的额外存储量不会被使用,而是为向量保留,以便在其增长时使用。通过这种方式,矢量不必在每次增长时重新分配存储,而是只有当这个额外的空间用完并插入一个新元素时(这只应以与其大小相关的对数频率发生)。

Reallocations may be a costly operation in terms of performance, since they generally involve the entire storage space used by the vector to be copied to a new location. Therefore, whenever large increases in size are planned for a vector, it is recommended to explicitly indicate a capacity for the vector using member function vector::reserve.
就性能而言,重新定位可能是一项成本高昂的操作,因为它们通常涉及要复制到新位置的向量所使用的整个存储空间。因此,每当计划大幅增加向量的大小时,建议使用成员函数vector::reserve明确指示向量的容量。

In their implementation in the C++ Standard Template Library vectors take two template parameters:
在C++标准模板库中实现时,矢量采用两个模板参数:
template < class T, class Allocator = allocator<T> > class vector;
 
Where the template parameters have the following meanings:


T: Type of the elements. 
Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent. 
分配器:用于定义存储分配模型的分配器对象的类型。默认情况下,使用类型T的分配器类模板,它定义了最简单的内存分配模型,并且与值无关。
In the reference for the vector member functions, these same names are assumed for the template parameters.
在向量成员函数的引用中,模板参数采用了这些相同的名称。

vector

explicit vector ( const Allocator& = Allocator() );
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
template <class InputIterator>
         vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
vector ( const vector<T,Allocator>& x ); <vector> 

Construct vector

Constructs a vector container object, initializing its contents depending on the constructor version used:


explicit vector ( const Allocator& = Allocator() ); 
Default constructor: constructs an empty vector, with no content and a size of zero. 
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); 
Repetitive sequence constructor: Initializes the vector with its content set to a repetition, n times, of copies of value. 
template <class InputIterator> vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() ); 
Iteration constructor: Iterates between first and last, setting a copy of each of the sequence of elements as the content of the container. 
vector ( const vector<T,Allocator>& x ); 
Copy constructor: The vector is initialized to have the same contents (copies) and properties as vector x. 

Parameters
n 
Times that value is repeated to form the content of the container object.
Member type size_type is an unsigned integral type. 
value 
Value to be repeated n times as the content of the container object.
T is the first class template parameter (the type of the elements stored in the vector). 
first, last 
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.
The function template type can be any type of input iterator. 

x 
Another vector object with the same class template parameters (T and Allocator).

unnamed Allocator parameter 
Allocator object to be used instead of constructing a new one.
For class instantiations using their version of the default allocator class template, this parameter is not relevant. 

Example
// constructing vectors
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;

  // constructors used in the same order as described above:
  vector<int> first;                                // empty vector of ints
  vector<int> second (4,100);                       // four ints with value 100
  vector<int> third (second.begin(),second.end());  // iterating through second
  vector<int> fourth (third);                       // a copy of third

  // the iterator constructor can also be used to construct from arrays:
  int myints[] = {16,2,77,29};
  vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

  cout << "The contents of fifth are:";
  for (i=0; i < fifth.size(); i++)
    cout << " " << fifth[i];

  cout << endl;

  return 0;
}
 
Output:
The contents of fifth are: 16 2 77 29  


Complexity
For the default constructor, constant.
For the repetitive sequence constructor, linear on n (copy constructions).
For the iterator constructor, linear on the distance between the iterators (copy constructions). If the iterators are forward, bidirectional or random-access, the capacity is determined before beginning, otherwise logarithmic complexity (object reallocations) must be added on top of that.
For the copy constructor, linear on x's size (copy constructions).

~vector();

operator=

vector<T,Allocator>& operator= (const vector<T,Allocator>& x);  

Copy vector content

Assigns a copy of vector x as the new content for the vector object.

The elements contained in the vector object before the call are dropped, and replaced by copies of those in vector x, if any.

After a call to this member function, both the vector object and vector x will have the same size and compare equal to each other.


Parameters
x 
A vector object containing elements of the same type. 

Return value
*this

Example
// vector assignment
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> first (3,0);
  vector<int> second (5,0);

  second=first;
  first=vector<int>();

  cout << "Size of first: " << int (first.size()) << endl;
  cout << "Size of second: " << int (second.size()) << endl;
  return 0;
}
 
Both vectors of int elements are initialized to sequences of zeros of different sizes. Then, second is assigned to first, so both are now equal and with a size of 3. And then, first is assigned to a newly constructed empty object, so its size is finally 0.
Output:
Size of first: 0
Size of second: 3 


Complexity
Linear on sizes (destruction, copy construction).

begin/end

 iterator begin ();
const_iterator begin () const;  

Return iterator to beginning

Returns an iterator referring to the first element in the vector container.

Notice that unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator.


Parameters
none

Return Value
An iterator to the beginning of the sequence.
Both iterator and const_iterator are member types. In the vector class template, these are random access iterators.


Example
// vector::begin
#include <iostream>
#include <vector>
using namespace std;

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

  vector<int>::iterator it;

  cout << "myvector contains:";
  for ( it=myvector.begin() ; it < myvector.end(); it++ )
    cout << " " << *it;

  cout << endl;

  return 0;
}
 

Output:
myvector contains: 1 2 3 4 5 



Complexity
Constant.

rbegin/rend

 reverse_iterator rbegin();
const_reverse_iterator rbegin() const;  

Return reverse iterator to reverse beginning

Returns a reverse iterator referring to the last element in the vector container.

rbegin refers to the element right before the one that would be referred to by member end.

Notice that unlike member vector::back, which returns a reference to this same element, this function returns a reverse random access iterator.


Parameters
none

Return Value
A reverse iterator to the reverse beginning of the sequence.
Both reverse_iterator and const_reverse_iterator are member types. In the vector class template, these are reverse random access iterators, defined as reverse_iterator<iterator> and reverse_iterator<const_iterator> respectivelly.


Example
// vector::rbegin/rend
#include <iostream>
#include <vector>
using namespace std;

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

  cout << "myvector contains:";
  vector<int>::reverse_iterator rit;
  for ( rit=myvector.rbegin() ; rit < myvector.rend(); ++rit )
    cout << " " << *rit;

  cout << endl;

  return 0;
}
 

Notice how the reverse iterator iterates through the vector in a reverse way by increasing the iterator. Output:
myvector contains: 5 4 3 2 1 



Complexity
Constant.

size

size_type size() const;  

Return size

Returns the number of elements in the vector container.

This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. Vectors automatically reallocate their storage space when needed or when requested with member resize. To retrieve the current storage capacity of a vector you can call to its member capacity.


Parameters
none

Return Value
The number of elements that conform the vector's content.
Member type size_type is an unsigned integral type.


Example
// vector::size
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myints;
  cout << "0. size: " << (int) myints.size() << endl;

  for (int i=0; i<10; i++) myints.push_back(i);
  cout << "1. size: " << (int) myints.size() << endl;

  myints.insert (myints.end(),10,100);
  cout << "2. size: " << (int) myints.size() << endl;

  myints.pop_back();
  cout << "3. size: " << (int) myints.size() << endl;

  return 0;
}
 

Output:
0. size: 0
1. size: 10
2. size: 20
3. size: 19 



Complexity
Constant.

max_size

size_type max_size () const;  

Return maximum size

Returns the maximum number of elements that the vector container can hold.

This is not the amount of storage space currently allocated to the vector (this can be obtained with member vector::capacity), but the maximum potential size the vector could reach due to system or library implementation limitations.


Parameters
none

Return Value
The maximum number of elements a vector object can have as its content.
Member type size_type is an unsigned integral type.


Example
// comparing size, capacity and max_size
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  cout << "size: " << (int) myvector.size() << "\n";
  cout << "capacity: " << (int) myvector.capacity() << "\n";
  cout << "max_size: " << (int) myvector.max_size() << "\n";
  return 0;
}
 

A possible output for this program could be:
size: 100
capacity: 141
max_size: 1073741823 



Complexity
Constant.

resize

void resize ( size_type sz, T c = T() );  

Change size

Resizes the vector to contain sz elements.

If sz is smaller than the current vector size, the content is reduced to its first sz elements, the rest being dropped.

If sz is greater than the current vector size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. This may cause a reallocation.

Notice that this function changes the actual content of the vector by inserting or erasing elements from the vector; It does not only change its storage capacity. To direct a change only in storage capacity, use vector::reserve instead.


Parameters
sz 
New vector size, expressed in elements.
Member type size_type is an unsigned integral type. 
c 
Object whose content is copied to the added elements in case that sz is greater than the current vector size.
If not specified, the default constructor is used.
T is the first template parameter (the type of the elements stored in the vector). 

Return Value
none
If a reallocation happens, it is performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// resizing vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  unsigned int i;

  // set some initial content:
  for (i=1;i<10;i++) myvector.push_back(i);

  myvector.resize(5);
  myvector.resize(8,100);
  myvector.resize(12);

  cout << "myvector contains:";
  for (i=0;i<myvector.size();i++)
    cout << " " << myvector[i];

  cout << endl;

  return 0;
}
 

The code sets a sequence of 9 numbers as an initial content for myvector. It then uses resize first to trim the vector to a size of 5, then to extend its size to 8 with values of 100 for its new elements, and finally it extends its size to 12 with their default values (for int elements this is zero).
该代码将一个由9个数字组成的序列设置为myvector的初始内容。然后,它首先使用resize将向量修剪到5的大小,然后将其大小扩展到8,新元素的值为100,最后将其大小使用默认值扩展到12(对于int元素,这是零)。
Output:
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0 

capacity

size_type capacity () const;  

Return size of allocated storage capacity

Returns the size of the allocated storage space for the elements of the vector container.

Notice that, in vectors, the capacity is not necessarily equal to the number of elements that conform the underlying vector content (this can be obtained with member vector::size), but the capacity of the actual allocated space, which is either equal or greater than the content size.

Notice also that this capacity does not suppose a limit to the size of the vector. If more space is required to accomodate new elements in the vector, the capacity is automatically expanded, or can even be explicitly modified by calling member vector::reserve.

The real limit on the size a vector object can reach is returned by member vector::max_size.


Parameters
none

Return Value
The size of the currently allocated storage capacity in the vector, measured in the number elements it could hold.
Member type size_type is an unsigned integral type.


Example
// comparing size, capacity and max_size
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  cout << "size: " << (int) myvector.size() << "\n";
  cout << "capacity: " << (int) myvector.capacity() << "\n";
  cout << "max_size: " << (int) myvector.max_size() << "\n";
  return 0;
}
 

A possible output for this program could be:
size: 100
capacity: 141
max_size: 1073741823 

empty

bool empty () const;  

Test whether vector is empty

Returns whether the vector container is empty, i.e. whether its size is 0.

This function does not modify the content of the vector in any way. To clear the content of a vector, use vector::clear.


Parameters
none

Return Value
true if the vector size is 0, false otherwise.

Example
// vector::empty
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  int sum (0);

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

  while (!myvector.empty())
  {
     sum += myvector.back();
     myvector.pop_back();
  }

  cout << "total: " << sum << endl;
  
  return 0;
}
 
The example initializes the content of the vector to a sequence of numbers (form 1 to 10). It then pops the elements one by one until it is empty and calculates their sum.
Output:
total: 55 


reserve

void reserve ( size_type n );  

Request a change in capacity

Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements.

This informs the vector of a planned change in size, which can be either to expand or shrink its storage capacity, although notice that the parameter n informs of a minimum, so the resulting capacity may be any capacity equal or larger than this.

When n supposes an expansion in capacity, a reallocation happens during the call to this function, granting that no further automatic reallocations will happen because of a call to vector::insert or vector::push_back until the vector size surpasses at least n (this preserves the validity of iterators on these calls).

A reallocation invalidates all previously obtained iterators, references and pointers.

In any case, a call to this function never affects the elements contained in the vector, nor the vector size (for that purposes, see vector::resize or vector::erase, which modify the vector size and content).


Parameters
n 
Minimum amount desired as capacity of allocated storage.
Member type size_type is an unsigned integral type. 

Return Value
none
If the requested size to allocate is greater than the maximum size (vector::max_size) a length_error exception is thrown.

In case of reallocation, this is performed using Allocator::allocate(), which may throw its own exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// vector::reserve
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> content;
  size_t filesize;

  ifstream file ("test.bin",ios::in|ios::ate|ios::binary);
  if (file.is_open())
  {
    filesize=file.tellg();

    content.reserve(filesize);

    file.seekg(0);
    while (!file.eof())
    {
      content.push_back( file.get() );
    }

    // print out content:
    vector<int>::iterator it;
    for (it=content.begin() ; it<content.end() ; it++)
      cout << hex << *it;
  }

  return 0;
}
 

This example reserves enough capacity in a vector of ints to store the content of an entire file, which is then read character by character (each character stored as an element in the vector). By reserving a capacity for the vector of at least the size of the entire file, we avoid all the automatic reallocations that the object content could suffer each time that a new element surpassed the size of its previously allocated storage space.
本例在int向量中保留了足够的容量来存储整个文件的内容,然后逐字符读取(每个字符存储为向量中的一个元素)。通过为向量保留至少整个文件大小的容量,我们避免了每次新元素超过其先前分配的存储空间大小时对象内容可能遭受的所有自动重新分配。

operator[]

 reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;  

Access element

Returns a reference to the element at position n in the vector container.

A similar member function, vector::at, has the same behavior as this operator function, except that vector::at signals if the requested position is out of range by throwing an exception.


Parameters
n 
Position of an element in the vector.
Notice that the first element has a position of 0, not 1.
Member type size_type is an unsigned integral type. 

Return value
The element at the specified position in the vector.
Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectivelly in most storage allocation models).


Example
// vector::operator[]
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector (10);   // 10 zero-initialized elements
  unsigned int i;

  vector<int>::size_type sz = myvector.size();

  // assign some values:
  for (i=0; i<sz; i++) myvector[i]=i;

  // reverse vector using operator[]:
  for (i=0; i<sz/2; i++)
  {
    int temp;
    temp = myvector[sz-1-i];
    myvector[sz-1-i]=myvector[i];
    myvector[i]=temp;
  }

  cout << "myvector contains:";
  for (i=0; i<sz; i++)
    cout << " " << myvector[i];

  cout << endl;

  return 0;
}
 

Output:
myvector contains: 9 8 7 6 5 4 3 2 1 0 

at

const_reference at ( size_type n ) const;
      reference at ( size_type n );  

Access element

Returns a reference to the element at position n in the vector.

The difference between this member function and member operator function operator[] is that vector::at signals if the requested position is out of range by throwing an out_of_range exception.


Parameters
n 
Position of an element in the vector.
If this is greater than the vector size, an exception of type out_of_range is thrown.
Notice that the first element has a position of 0, not 1.
Member type size_type is an unsigned integral type. 

Return value
The element at the specified position in the vector.
Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model, allocator, these are T& and const T& respectively).


Example
// vector::at
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector (10);   // 10 zero-initialized ints
  unsigned int i;

  // assign some values:
  for (i=0; i<myvector.size(); i++)
    myvector.at(i)=i;

  cout << "myvector contains:";
  for (i=0; i<myvector.size(); i++)
    cout << " " << myvector.at(i);

  cout << endl;

  return 0;
}
 

Output:
myvector contains: 0 1 2 3 4 5 6 7 8 9 

font

 reference front ( );
const_reference front ( ) const;  

Access first element

Returns a reference to the first element in the vector container.

Unlike member vector::begin, which returns an iterator to this same element, this function returns a direct reference.


Parameters
none

Return value
A reference to the first element in the vector.
Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model, allocator, these are T& and const T& respectively).


Example
// vector::front
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  myvector.push_back(77);
  myvector.push_back(16);

  // now front equals 77, and back 16

  myvector.front() -= myvector.back();

  cout << "myvector.front() is now " << myvector.front() << endl;

  return 0;
}
 

Output:
myvector.front() is now 61 

back

 reference back ( );
const_reference back ( ) const;  

Access last element

Returns a reference to the last element in the vector container.

Unlike member vector::end, which returns an iterator just past this element, this function returns a direct reference.


Parameters
none

Return value
A reference to the last element in the vector.
Member types reference and const_reference are the reference types to the elements of the vector container (for the default storage allocation model, allocator, these are T& and const T& respectively).


Example
// vector::back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  myvector.push_back(10);

  while (myvector.back() != 0)
  {
    myvector.push_back ( myvector.back() -1 );
  }

  cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size() ; i++)
    cout << " " << myvector[i];

  cout << endl;

  return 0;
}
 

Output:
myvector contains: 10 9 8 7 6 5 4 3 2 1 0 

assign

template <class InputIterator>
  void assign ( InputIterator first, InputIterator last );
void assign ( size_type n, const T& u );  

Assign vector content

Assigns new content to the vector object, dropping all the elements contained in the vector before the call and replacing them by those specified by the parameters:

In the first version (with iterators), the new contents are a copy of the elements in the sequence between first and last (in the range [first,last)).

In the second version, the new content is the repetition n times of copies of element u.


Parameters
first, last 
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.
The template type can be any type of input iterator. 
n 
Times that u is repeated to form the new content of the object.
Member type size_type is an unsigned integral type. 
u 
Value to be repeated n times as the new content of the object.
T is the first class template parameter (the type of the elements stored in the vector). 

Return value
none

Example
// vector assign
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> first;
  vector<int> second;
  vector<int> third;

  first.assign (7,100);             // a repetition 7 times of value 100

  vector<int>::iterator it;
  it=first.begin()+1;

  second.assign (it,first.end()-1); // the 5 central values of first

  int myints[] = {1776,7,4};
  third.assign (myints,myints+3);   // assigning from array.

  cout << "Size of first: " << int (first.size()) << endl;
  cout << "Size of second: " << int (second.size()) << endl;
  cout << "Size of third: " << int (third.size()) << endl;
  return 0;
}
 
Output:
Size of first: 7
Size of second: 5
Size of third: 3 


Complexity
Linear on initial and final sizes (destruction, copy construction).
In the case of the iteration version, if the iterators are forward, bidirectional or random-access, the new capacity is determined before beginning, otherwise logarithmic complexity (object reallocations) must be added on top of that.

push_back

void push_back ( const T& x );  

Add element at the end

Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x.

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call. Reallocations invalidate all previously obtained iterators, references and pointers.


Parameters
x 
Value to be copied to the new element.
T is the first template parameter (the type of the elements stored in the vector). 

Return value
none
If a reallocation happens, it is performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// vector::push_back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  int myint;

  cout << "Please enter some integers (enter 0 to end):\n";

  do {
    cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  cout << "myvector stores " << (int) myvector.size() << " numbers.\n";

  return 0;
}
 
The example uses push_back to add a new element to the vector each time a new integer is read.

pop_back

void pop_back ( );  

Delete last element

Removes the last element in the vector, effectively reducing the vector size by one and invalidating all iterators and references to it.

This calls the removed element's destructor.


Parameters
none

Return value
none

Example
// vector::pop_back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  int sum (0);
  myvector.push_back (100);
  myvector.push_back (200);
  myvector.push_back (300);

  while (!myvector.empty())
  {
    sum+=myvector.back();
    myvector.pop_back();
  }

  cout << "The elements of myvector summed " << sum << endl;

  return 0;
}
 
In this example, the elements are popped out of the vector after they are added up in the sum. Output:
The elements of myvector summed 600 

insert

iterator insert ( iterator position, const T& x );
    void insert ( iterator position, size_type n, const T& x );
template <class InputIterator>
    void insert ( iterator position, InputIterator first, InputIterator last );  

Insert elements

The vector is extended by inserting new elements before the element at position.

This effectively increases the vector size, which causes an automatic reallocation of the allocated storage space if, and only if, the new vector size surpases the current vector capacity. Reallocations in vector containers invalidate all previously obtained iterators, references and pointers.

Because vectors keep an array format, insertions on positions other than the vector end are performed by moving all the elements between position and the end of the vector to their new positions, and then inserting the new element(s), which may not be a method as efficient as the insertion in other kinds of sequence containers (deque, list).

The parameters determine how many elements are inserted and to which values they are initialized:


Parameters
position 
Position in the vector where the new elements are inserted.
iterator is a member type, defined as a random access iterator type. 
x 
Value to be used to initialize the inserted elements.
T is the first template parameter (the type of the elements stored in the vector). 
n 
Number of elements to insert. Each element is initialized to the value specified in x.
Member type size_type is an unsigned integral type. 
first, last 
Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position position.
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The template type can be any type of input iterator. 

Return value
Only the first version returns a value, which is an iterator that points to the newly inserted element.
If reallocations happen, they are performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).


Example
// inserting into a vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector (3,100);
  vector<int>::iterator it;

  it = myvector.begin();
  it = myvector.insert ( it , 200 );

  myvector.insert (it,2,300);

  // "it" no longer valid, get a new one:
  it = myvector.begin();

  vector<int> anothervector (2,400);
  myvector.insert (it+2,anothervector.begin(),anothervector.end());

  int myarray [] = { 501,502,503 };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    cout << " " << *it;
  cout << endl;

  return 0;
}
 
Output:
myvector contains: 501 502 503 300 300 400 400 200 100 100 100 

erase

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );  

Erase elements

Removes from the vector container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

This invalidates all iterator and references to elements after position or first.


Parameters
All parameters are of member type iterator, which in vector containers are defined as a random access iterator type.

position 
Iterator pointing to a single element to be removed from the vector. 
first, last 
Iterators specifying a range within the vector to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. 

Return value
A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.

Example
// erasing from vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;
  vector<unsigned int> myvector;

  // set some values (from 1 to 10)
  for (i=1; i<=10; i++) myvector.push_back(i);
  
  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);

  cout << "myvector contains:";
  for (i=0; i<myvector.size(); i++)
    cout << " " << myvector[i];
  cout << endl;

  return 0;
}
 
Output:
myvector contains: 4 5 7 8 9 10 

swap

void swap ( vector<T,Allocator>& vec );  

Swap content

Exchanges the content of the vector by the content of vec, which is another vector of the same type. Sizes may differ.

After the call to this member function, the elements in this container are those which were in vec before the call, and the elements of vec are those which were in this. All iterators, references and pointers remain valid for the swapped vectors.

Notice that a global algorithm function exists with this same name, swap, and the same behavior.


Parameters
vec 
Another vector container of the same type as this whose content is swapped with that of this container. 

Return value
none

Example
// swap vectors
#include <iostream>
#include <vector>
using namespace std;

main ()
{
  unsigned int i;
  vector<int> first (3,100);   // three ints with a value of 100
  vector<int> second (5,200);  // five ints with a value of 200

  first.swap(second);

  cout << "first contains:";
  for (i=0; i<first.size(); i++) cout << " " << first[i];

  cout << "\nsecond contains:";
  for (i=0; i<second.size(); i++) cout << " " << second[i];

  cout << endl;

  return 0;
}
 

Output:
first contains: 200 200 200 200 200 
second contains: 100 100 100  

clear

void clear ( );  

Clear content

All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.


Parameters
none

Return value
none

Example
// clearing vectors
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;
  vector<int> myvector;
  myvector.push_back (100);
  myvector.push_back (200);
  myvector.push_back (300);

  cout << "myvector contains:";
  for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];

  myvector.clear();
  myvector.push_back (1101);
  myvector.push_back (2202);

  cout << "\nmyvector contains:";
  for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];

  cout << endl;

  return 0;
}
 

Output:
myvector contains: 100 200 300
myvector contains: 1101 2202 

get_allocator

allocator_type get_allocator() const;  

Get allocator

Returns the allocator object used to constuct the vector.


Parameters
none

Return Value
The allocator.
Member type allocator_type is defined to the same as the second template parameter used to instantitate this specific vector class (its Allocator type).


Example
// vector::get_allocator
#include <iostream>
#include <vector>

using namespace std;

int main ()
{
  vector<int> myvector;
  int * p;
  unsigned int i;

  // allocate an array of 5 elements using vector's allocator:
  p=myvector.get_allocator().allocate(5);

  // assign some values to array
  for (i=0; i<5; i++) p[i]=i;

  cout << "The allocated array contains:";
  for (i=0; i<5; i++) cout << " " << p[i];
  cout << endl;

  myvector.get_allocator().deallocate(p,5);

  return 0;
}
 
The example shows an elaborate way to allocate memory for an array of ints using the same allocator used by the vector. 
Output:
The allocated array contains: 0 1 2 3 4 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值