C++容器 I 向量

//class template <vector> std::vector
template < class T, class Alloc = allocator<T> > class vector; 
// generic template
模板参数【Template parameters】
T

元素的类型。

只有保证T在移动时不会抛出,实现才能优化以移动元素,而不是在重新分配期间复制它们。

别名为成员类型vector::value_type。

Alloc

用于定义存储分配模型的分配器对象的类型。默认情况下,使用分配器类模板,它定义了最简单的内存分配模型,并且与值无关。

别名为成员类型vector::allocator_type。

向量【Vector】

Vectors are sequence containers representing arrays that can change in size.

向量是序列容器,表示可以改变大小的数组。

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

与数组一样,向量使用连续的存储位置存储其元素,这意味着也可以使用指向其元素的常规指针上的偏移量来访问其元素,其效率与数组中的相同。但与数组不同,它们的大小可以动态变化,其存储由容器自动处理。

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

在内部,向量使用一个动态分配的数组来存储它们的元素。当插入新元素时,可能需要重新分配该数组,以便增大其大小,这意味着分配一个新数组并将所有元素移动到该数组中。就处理时间而言,这是一项相对昂贵的任务,因此,向量不会在每次将元素添加到容器时重新分配。

Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back).

相反,载体容器可能会分配一些额外的存储空间,以适应可能的增长,因此容器的实际容量可能会大于严格需要的存储空间,以容纳其元素(即其大小)。库可以实现不同的增长策略,以平衡内存使用和重新分配,但在任何情况下,重新分配只应以对数增长的大小间隔进行,以便在向量末尾插入单个元素时,可以提供摊销的恒定时间复杂度(参见push_back)。

Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

因此,与数组相比,向量消耗更多内存,以换取以高效方式管理存储和动态增长的能力。

Compared to the other dynamic sequence containers (deques, lists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists.

与其他动态序列容器(deques、list和forward_list)相比,向量非常高效地访问其元素(就像数组一样),并且相对高效地从其末端添加或删除元素。对于涉及在端点以外的位置插入或删除元素的操作,它们的性能比其他操作差,并且与列表和转发列表相比,迭代器和引用的一致性较差。

容器属性【Container properties】
序列【Sequence】

Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence.

序列容器中的元素按严格的线性序列排序。单个元素通过它们在该序列中的位置来访问。

动态数组【Dynamic array】

Allows direct access to any element in the sequence, even through pointer arithmetics, and provides relatively fast addition/removal of elements at the end of the sequence.

允许直接访问序列中的任何元素,即使是通过指针算术,并在序列末尾相对快速地添加/删除元素。

分配器感知【Allocator-aware】

The container uses an allocator object to dynamically handle its storage needs.

容器使用分配器对象动态处理其存储需求。

成员类型【Member types】
memeber type definition notes
value_type The first template parameter (T)
allocator_type The second template parameter (Alloc) defaults to: allocator<value_type>
reference allocator_type::reference for the default allocator: value_type&
const_reference allocator_type::const_reference for the default allocator: const value_type&
pointer allocator_type::pointer for the default allocator: value_type*
const_pointer allocator_type::const_pointer for the default allocator: const value_type*
iterator a random access iterator to value_type convertible to const_iterator
const_iterator a random access iterator to const value_type
reverse_iterator reverse_iterator
const_reverse_iterator reverse_iterator<const_iterator>
difference_type a signed integral type, identical to: iterator_traits::difference_type usually the same as ptrdiff_t
size_type an unsigned integral type that can represent any non-negative value of difference_type usually the same as size_t

成员函数【Member functions】

(constructor)

构造向量(公共成员函数)

实例【Example】
  // constructing vectors
#include <iostream>
#include <vector>

int main ()
{
  // constructors used in the same order as described above:
  std::vector<int> first;                                // empty vector of ints
  std::vector<int> second (4,100);                       // four ints with value 100
  std::vector<int> third (second.begin(),second.end());  // iterating through second
  std::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};
  std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

  std::cout << "The contents of fifth are:";
  for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Output】

The contents of fifth are: 16 2 77 29

default (1)
explicit vector (const allocator_type& alloc = allocator_type());
  
fill (2)
explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());
  
range (3)
template <class InputIterator>
         vector (InputIterator first, InputIterator last,
                 const allocator_type& alloc = allocator_type());

copy (4)
vector (const vector& x);

参数【Parameters】
alloc

分配器对象。

容器保存并使用此分配器的内部副本。

Member type allocator_type是容器使用的内部分配器类型,在vector中定义为其第二个模板参数(Alloc)的别名。

如果allocator_type是默认分配器(没有状态)的实例化,则这与此无关。

n

初始容器尺寸(即,施工时容器中的元素数量)。

成员类型size_type是无符号整数类型。

val

值来填充容器。容器中的n个元素中的每一个都将被初始化为该值的副本。

成员类型value_type是容器中元素的类型,在vector中定义为其第一个模板参数(T)的别名。

first, last

将迭代器输入到范围内的初始和最终位置。使用的范围是[first,last],它包括first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

函数模板参数InputIterator应该是一种输入迭代器类型,它指向可以构造value_类型对象的类型元素。

x

另一个相同类型的向量对象(具有相同的类模板参数T和Alloc),其内容被复制或获取。

构造向量【Construct vector】

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

构造一个向量,根据使用的构造函数版本初始化其内容:

(1) 空容器构造函数(默认构造函数)

构造一个没有元素的空容器。

(2) 填充构造函数

构造一个包含n个元素的容器。每个元素都是val的副本。

(3) 范围构造函数

构造一个容器,容器中的元素数量与范围[first,last]相同,每个元素都是从该范围内对应的元素以相同的顺序构造的。

(4) 复制构造函数

以相同的顺序构造一个容器,其中包含x中每个元素的副本。

容器保留alloc的内部副本,用于在其整个生命周期内分配存储。

复制构造函数(4)创建一个容器,该容器保存并使用x的分配器的副本。

元素的存储是使用这个内部分配器分配的。

(destructor)

向量析构函数(公共成员函数)

operator=

分配公共内容功能(成员)

实例【Example】
// vector assignment
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> foo (3,0);
  std::vector<int> bar (5,0);

  bar = foo;
  foo = std::vector<int>();

  std::cout << "Size of foo: " << int(foo.size()) << '\n';
  std::cout << "Size of bar: " << int(bar.size()) << '\n';
  return 0;
}
输出【Output】

Size of foo: 0

Size of bar: 3

copy (1)
vector& operator= (const vector& x);
参数【Parameters】
x

相同类型的向量对象(即具有相同的模板参数T和Alloc)。

分配内容【Assign content】

Assigns new contents to the container, replacing its current contents, and modifying its size accordingly.

将新内容分配给容器,替换其当前内容,并相应地修改其大小。

Copies all the elements from x into the container.

将x中的所有元素复制到容器中。

The container preserves its current allocator, which is used to allocate storage in case of reallocation.

容器保留其当前分配器,用于在重新分配时分配存储。

Any elements held in the container before the call are either assigned to or destroyed.

在调用之前,容器中保存的任何元素都会被分配或销毁。

迭代器【Iterators】

begin

将迭代器返回到开头(公共成员函数)

实例【Example】
// vector::begin/end
#include <iostream>
#include <vector>

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

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 1 2 3 4 5

将迭代器返回到开头【Return iterator to beginning】

Returns an iterator pointing to the first element in the vector.

返回指向向量中第一个元素的迭代器。

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

请注意,与返回对第一个元素的引用的member vector::front不同,该函数返回指向它的随机访问迭代器。

If the container is empty, the returned iterator value shall not be dereferenced.

如果容器为空,则返回的迭代器值不应被取消引用。

end

返回迭代器结束(公共成员函数)

实例【Example】
// vector::begin/end
#include <iostream>
#include <vector>

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

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 1 2 3 4 5

返回迭代器结束【Return iterator to end】

Returns an iterator referring to the past-the-end element in the vector container.

返回一个迭代器,该迭代器引用向量容器中结束元素的过去部分。

The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

结束元素的过去是向量中最后一个元素之后的理论元素。它不指向任何元素,因此不应取消引用。

Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container.

由于标准库函数使用的范围不包括其结束迭代器所指向的元素,因此此函数通常与vector::begin结合使用,以指定一个范围,该范围包括容器中的所有元素。

If the container is empty, this function returns the same as vector::begin.

如果容器为空,此函数将返回与vector::begin相同的结果。

rbegin

将反向迭代器返回到反向开始(公共成员函数)

实例【Example】
// vector::rbegin/rend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);  // 5 default-constructed ints

  int i=0;

  std::vector<int>::reverse_iterator rit = myvector.rbegin();
  for (; rit!= myvector.rend(); ++rit)
    *rit = ++i;

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 5 4 3 2 1

返回反向迭代器以反向开始【Return reverse iterator to reverse beginning】

Returns a reverse iterator pointing to the last element in the vector (i.e., its reverse beginning).

返回一个反向迭代器,该迭代器指向向量中的最后一个元素(即其反向开头)。

Reverse iterators iterate backwards: increasing them moves them towards the beginning of the container.

反向迭代器向后迭代:增加它们会将它们移到容器的开头。

rbegin points to the element right before the one that would be pointed to by member end.

rbegin指向成员端将指向的元素之前的元素。

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

请注意,与返回对同一元素的引用的member vector::back不同,该函数返回一个反向随机访问迭代器。

rend

返回反向迭代器到反向结束(公共成员函数)

实例【Example】
// vector::rbegin/rend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);  // 5 default-constructed ints

  int i=0;

  std::vector<int>::reverse_iterator rit = myvector.rbegin();
  for (; rit!= myvector.rend(); ++rit)
    *rit = ++i;

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 5 4 3 2 1

将反向迭代器返回到反向结束【Return reverse iterator to reverse end】

Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (which is considered its reverse end).

返回一个反向迭代器,该迭代器指向向量中第一个元素之前的理论元素(该元素被视为其反向端点)。

The range between vector::rbegin and vector::rend contains all the elements of the vector (in reverse order).

vector::rbegin和vector::rend之间的范围包含向量的所有元素(顺序相反)。

cbegin

将常量迭代器返回到开头(公共成员函数)

实例【Example】
// vector::cbegin/cend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30,40,50};

  std::cout << "myvector contains:";

  for (auto it = myvector.cbegin(); it != myvector.cend(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 10 20 30 40 50

将常量迭代器返回到开头【Return const_iterator to beginning】

Returns a const_iterator pointing to the first element in the container.

返回指向容器中第一个元素的常量迭代器。

A const_iterator is an iterator that points to const content. This iterator can be increased and decreased (unless it is itself also const), just like the iterator returned by vector::begin, but it cannot be used to modify the contents it points to, even if the vector object is not itself const.

常量迭代器是指向常量内容的迭代器。这个迭代器可以增加和减少(除非它本身也是常量),就像vector::begin返回的迭代器一样,但它不能用于修改它指向的内容,即使vector对象本身不是常量。

If the container is empty, the returned iterator value shall not be dereferenced.

如果容器为空,则返回的迭代器值不应被取消引用。

cend

返回常量迭代器结束(公共成员函数)

实例【Example】
// vector::cbegin/cend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30,40,50};

  std::cout << "myvector contains:";

  for (auto it = myvector.cbegin(); it != myvector.cend(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector contains: 10 20 30 40 50

返回常量迭代器结束【Return const_iterator to end】

Returns a const_iterator pointing to the past-the-end element in the container.

返回一个常量迭代器,该迭代器指向容器中结束元素的过去。

A const_iterator is an iterator that points to const content. This iterator can be increased and decreased (unless it is itself also const), just like the iterator returned by vector::end, but it cannot be used to modify the contents it points to, even if the vector object is not itself const.

常量迭代器是指向常量内容的迭代器。这个迭代器可以增减(除非它本身也是常量),就像vector::end返回的迭代器一样,但它不能用于修改它指向的内容,即使vector对象本身不是常量。

If the container is empty, this function returns the same as vector::cbegin.

如果容器为空,则此函数返回与vector::cbegin相同的值。

The value returned shall not be dereferenced.

返回的值不得取消引用。

crbegin

返回const_reverse_迭代器以反转开始(公共成员函数)

实例【Example】
// vector::crbegin/crend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {1,2,3,4,5};

  std::cout << "myvector backwards:";
  for (auto rit = myvector.crbegin(); rit != myvector.crend(); ++rit)
    std::cout << ' ' << *rit;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector backwards: 5 4 3 2 1

返回const_reverse_迭代器以反转开始【Return const_reverse_iterator to reverse beginning】

Returns a const_reverse_iterator pointing to the last element in the container (i.e., its reverse beginning).

返回指向容器中最后一个元素(即其反向开头)的常量反迭代器。

crend

返回const_reverse_迭代器到reverse end(公共成员函数)

实例【Example】
// vector::crbegin/crend
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {1,2,3,4,5};

  std::cout << "myvector backwards:";
  for (auto rit = myvector.crbegin(); rit != myvector.crend(); ++rit)
    std::cout << ' ' << *rit;
  std::cout << '\n';

  return 0;
}
输出【Outut】

myvector backwards: 5 4 3 2 1

返回const_reverse_迭代器到reverse end【Return const_reverse_iterator to reverse end】

Returns a const_reverse_iterator pointing to the theoretical element preceding the first element in the container (which is considered its reverse end).

返回一个const_reverse_迭代器,该迭代器指向容器中第一个元素之前的理论元素(被视为其反向端)。

迭代器【Iterators】

size

返回大小(公共成员函数)

实例【Example】
// vector::size
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myints;
  std::cout << "0. size: " << myints.size() << '\n';

  for (int i=0; i<10; i++) myints.push_back(i);
  std::cout << "1. size: " << myints.size() << '\n';

  myints.insert (myints.end(),10,100);
  std::cout << "2. size: " << myints.size() << '\n';

  myints.pop_back();
  std::cout << "3. size: " << myints.size() << '\n';

  return 0;
}
输出【Output】
  1. size: 0
  2. size: 10
  3. size: 20
  4. size: 19
返回大小【Return size】

Returns the number of elements in the vector.

返回向量中的元素数。

This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.

这是向量中实际对象的数量,不一定等于其存储容量。

max_size

返回最大大小(公共成员函数)

实例【Example】
// comparing size, capacity and max_size
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

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

  std::cout << "size: " << myvector.size() << "\n";
  std::cout << "capacity: " << myvector.capacity() << "\n";
  std::cout << "max_size: " << myvector.max_size() << "\n";
  return 0;
}
输出【Output】

size: 100

capacity: 128

max_size: 1073741823

返回最大大小【Return maximum size】

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

返回向量可以容纳的最大元素数。

This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached.

由于已知的系统或库实现限制,这是容器可以达到的最大潜在大小,但容器并不能保证能够达到该大小:在达到该大小之前,它仍然可能无法在任何时候分配存储。

resize

更改大小(公共成员功能)

实例【Example】
// resizing vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

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

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

  std::cout << "myvector contains:";
  for (int i=0;i<myvector.size();i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}
输出【Output】

myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0

改变大小【Change size】

Resizes the container so that it contains n elements.

调整容器大小,使其包含n个元素。

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

如果n小于当前容器大小,则内容将减少到其前n个元素,并删除超出的元素(并销毁它们)。

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

如果n大于当前容器大小,则通过在末尾插入所需数量的元素来扩展内容,以达到n的大小。如果指定了val,则新元素将初始化为val的副本,否则,它们将被值初始化。

If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.

如果n也大于当前容器容量,则会自动重新分配分配的存储空间。

Notice that this function changes the actual content of the container by inserting or erasing elements from it.

请注意,此函数通过插入或删除容器中的元素来更改容器的实际内容。

capacity

已分配存储容量的返回大小(公共成员函数)

实例【Example】
// comparing size, capacity and max_size
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

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

  std::cout << "size: " << myvector.size() << "\n";
  std::cout << "capacity: " << myvector.capacity() << "\n";
  std::cout << "max_size: " << myvector.max_size() << "\n";
  return 0;
}
输出【Output】

size: 100

capacity: 128

max_size: 1073741823

返回已分配存储容量的大小【Return size of allocated storage capacity】

Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

返回当前分配给向量的存储空间大小,以元素表示。

This capacity is not necessarily equal to the vector size. It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.

这个容量不一定等于向量大小。它可以相等或更大,额外的空间可以容纳增长,而无需在每次插入时重新分配。

Notice that this capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size.

请注意,这个容量并不假设向量的大小有限制。当这个容量耗尽并且需要更多容量时,它会被容器自动扩展(重新分配存储空间)。向量大小的理论极限由成员max_size给出。

The capacity of a vector can be explicitly altered by calling member vector::reserve.

可以通过调用成员vector::reserve显式更改向量的容量。

empty

测试向量是否为空(公共成员函数)

实例【Example】
// vector::empty
#include <iostream>
#include <vector>

int main ()
{
  std::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();
  }

  std::cout << "total: " << sum << '\n';

  return 0;
}
输出【Output】

total: 55

测试向量是否为空【Test whether vector is empty】

Returns whether the vector is empty (i.e. whether its size is 0).

返回向量是否为空(即其大小是否为0)。

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

此函数不会以任何方式修改容器。要清除向量的内容,请参见vector::clear。

reserve

请求更改容量(公共成员功能)

实例【Example】
// vector::reserve
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int>::size_type sz;

  std::vector<int> foo;
  sz = foo.capacity();
  std::cout << "making foo grow:\n";
  for (int i=0; i<100; ++i) {
    foo.push_back(i);
    if (sz!=foo.capacity()) {
      sz = foo.capacity();
      std::cout << "capacity changed: " << sz << '\n';
    }
  }

  std::vector<int> bar;
  sz = bar.capacity();
  bar.reserve(100);   // this is the only difference with foo above
  std::cout << "making bar grow:\n";
  for (int i=0; i<100; ++i) {
    bar.push_back(i);
    if (sz!=bar.capacity()) {
      sz = bar.capacity();
      std::cout << "capacity changed: " << sz << '\n';
    }
  }
  return 0;
}
输出【Output】

making foo grow:

capacity changed: 1

capacity changed: 2

capacity changed: 4

capacity changed: 8

capacity changed: 16

capacity changed: 32

capacity changed: 64

capacity changed: 128

making bar grow:

capacity changed: 100

请求更改容量【Request a change in capacity】

Requests that the vector capacity be at least enough to contain n elements.

请求向量容量至少足以包含n个元素。

If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).

如果n大于当前向量容量,该函数将使容器重新分配其存储,并将其容量增加到n(或更大)。

In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.

在所有其他情况下,函数调用不会导致重新分配,向量容量也不会受到影响。

This function has no effect on the vector size and cannot alter its elements.

此函数对向量大小没有影响,并且不能更改其元素。

shrink_to_fit 

收缩到合适的尺寸(公共成员功能)

实例【Example】
// vector::shrink_to_fit
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (100);
  std::cout << "1. capacity of myvector: " << myvector.capacity() << '\n';

  myvector.resize(10);
  std::cout << "2. capacity of myvector: " << myvector.capacity() << '\n';

  myvector.shrink_to_fit();
  std::cout << "3. capacity of myvector: " << myvector.capacity() << '\n';

  return 0;
}
输出【Output】
  1. capacity of myvector: 100
  2. capacity of myvector: 100
  3. capacity of myvector: 10
收缩以适应【Shrink to fit】

Requests the container to reduce its capacity to fit its size.

请求容器减小容量以适应其大小。

The request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.

请求是非绑定的,容器实现可以自由地进行其他优化,并使向量的容量大于其大小。

This may cause a reallocation, but has no effect on the vector size and cannot alter its elements.

这可能会导致重新分配,但对向量大小没有影响,并且无法改变其元素。

Element access:

operator[]

访问元素(公共成员功能)

实例【Example】
// vector::operator[]
#include <iostream>
#include <vector>

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

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

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

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

  std::cout << "myvector contains:";
  for (unsigned i=0; i<sz; i++)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}
输出【Output】

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

访问元素【Access element】

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

返回向量容器中位置n处元素的引用。

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

类似的成员函数vector::at的行为与此运算符函数相同,只是vector::at被绑定检查,并通过抛出out_of_range异常来指示请求的位置是否超出范围。

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

可移植程序不应使用超出范围的参数n调用此函数,因为这会导致未定义的行为。

at

访问元素(公共成员功能)

实例【Example】
// vector::at
#include <iostream>
#include <vector>

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

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

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); i++)
    std::cout << ' ' << myvector.at(i);
  std::cout << '\n';

  return 0;
}
输出【Output】

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

访问元素【Access element】

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

返回对向量中位置n处元素的引用。

The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds.

该函数自动检查n是否在向量中有效元素的范围内,如果不在范围内(即,如果n大于或等于其大小),则抛出超出范围异常。这与不检查边界的成员运算符[]相反。

front

访问第一个元素(公共成员功能)

实例【Example】
// vector::front
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  myvector.push_back(78);
  myvector.push_back(16);

  // now front equals 78, and back 16

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

  std::cout << "myvector.front() is now " << myvector.front() << '\n';

  return 0;
}
输出【Output】

myvector.front() is now 62

访问第一元素【Access first element】

Returns a reference to the first element in the vector.

返回对向量中第一个元素的引用。

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

与向同一元素返回迭代器的member vector::begin不同,该函数返回直接引用。

Calling this function on an empty container causes undefined behavior.

在空容器上调用此函数会导致未定义的行为。

back

访问最后一个元素(公共成员函数)

实例【Example】
// vector::back
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  myvector.push_back(10);

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

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

  return 0;
}
输出【Output】

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

访问最后一个元素【Access last element】

Returns a reference to the last element in the vector.

返回对向量中最后一个元素的引用。

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

与member vector::end返回的迭代器刚好经过该元素不同,该函数返回的是直接引用。

Calling this function on an empty container causes undefined behavior.

在空容器上调用此函数会导致未定义的行为。

data 

访问数据(公共成员功能)

实例【Example】
// vector::data
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

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

  return 0;
}
输出【Output】

myvector contains: 10 20 0 100 0

访问数据【Access data】

Returns a direct pointer to the memory array used internally by the vector to store its owned elements.

返回指向向量内部用于存储其所属元素的内存数组的直接指针。

Because elements in the vector are guaranteed to be stored in contiguous storage locations in the same order as represented by the vector, the pointer retrieved can be offset to access any element in the array.

由于向量中的元素保证以向量表示的相同顺序存储在连续的存储位置,因此检索到的指针可以偏移以访问数组中的任何元素。

Modifiers:

assign

指定向量内容(公共成员函数)

range (1)
template <class InputIterator>
  void assign (InputIterator first, InputIterator last);
  
fill (2)
void assign (size_type n, const value_type& val);
变量【Parameters】
first, last

将迭代器输入序列中的初始和最终位置。使用的范围是[first,last),它包括first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

函数模板参数InputIterator应该是一种输入迭代器类型,它指向可以构造value_类型对象的类型元素。

n

容器的新尺寸。

成员类型size_type是无符号整数类型。

val

值来填充容器。容器中的n个元素中的每一个都将被初始化为该值的副本。

成员类型value_type是容器中元素的类型,在vector中定义为其第一个模板参数(T)的别名。

实例【Example】
// vector assign
#include <iostream>
#include <vector>

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

  first.assign (7,100);             // 7 ints with a value of 100

  std::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.

  std::cout << "Size of first: " << int (first.size()) << '\n';
  std::cout << "Size of second: " << int (second.size()) << '\n';
  std::cout << "Size of third: " << int (third.size()) << '\n';
  return 0;
}
输出【Output】

Size of first: 7

Size of second: 5

Size of third: 3

分配向量内容【Assign vector content】

Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly.

为向量指定新内容,替换其当前内容,并相应修改其大小。

push_back

在末尾添加元素(公共成员函数)

实例【Example】
// vector::push_back
#include <iostream>
#include <vector>

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

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

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

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

  return 0;
}
输出【Output】

该示例使用push_back在每次读取新整数时向向量添加新元素。

在末尾添加元素【Add element at the end】

Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.

在向量的最后一个元素之后,在向量的末尾添加新元素。val的内容被复制(或移动)到新元素中。

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

这将有效地将容器大小增加1,这将导致在新向量大小超过当前向量容量时(且仅当新向量大小超过当前向量容量时)自动重新分配分配分配的存储空间。

pop_back

删除最后一个元素(公共成员函数)

实例【Example】
// vector::pop_back
#include <iostream>
#include <vector>

int main ()
{
  std::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();
  }

  std::cout << "The elements of myvector add up to " << sum << '\n';

  return 0;
}
输出【Output】

The elements of myvector add up to 600

删除最后一个元素【Delete last element】

Removes the last element in the vector, effectively reducing the container size by one.

移除向量中的最后一个元素,有效地将容器大小减少一个。

This destroys the removed element.

这会破坏移除的元素。

insert

插入元素(公共成员函数)

  single element (1)
iterator insert (iterator position, const value_type& val);

  fill (2)
    void insert (iterator position, size_type n, const value_type& val);

  range (3)
template <class InputIterator>
    void insert (iterator position, InputIterator first, InputIterator last);
参数【Parameters】
position

在向量中插入新元素的位置。

迭代器是一种成员类型,定义为指向元素的随机访问迭代器类型。

val

要复制(或移动)到插入元素的值。

成员类型value_type是容器中元素的类型,在deque中定义为其第一个模板参数(T)的别名。

n

要插入的元素数。每个元素都初始化为val的一个副本。

成员类型size_type是无符号整数类型。

first, last

指定元素范围的迭代器。范围[first,last)中元素的副本插入位置(顺序相同)。

请注意,范围包括first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

函数模板参数InputIterator应该是一种输入迭代器类型,它指向可以构造value_类型对象的类型元素。

实例【Example】
// inserting into a vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (3,100);
  std::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();

  std::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);

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

  return 0;
}  
输出【Output】

myvector contains: 501 502 503 300 300 400 400 200 100 100 100

插入元素【Insert elements】

The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.

通过在指定位置的元素之前插入新元素来扩展向量,从而通过插入的元素数量有效地增加容器大小。

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

当且仅当新向量大小超过当前向量容量时,这会导致自动重新分配分配分配的存储空间。

Because vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

因为向量使用一个数组作为其底层存储,所以在向量末端以外的位置插入元素会导致容器将位置之后的所有元素重新定位到它们的新位置。与其他类型的序列容器(如list或forward_list)对同一操作执行的操作相比,这通常是一种效率低下的操作。

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

这些参数决定了插入的元素数量及其初始化值:

erase

删除元素(公共成员功能)

实例【Example】
// erasing from vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some values (from 1 to 10)
  for (int 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);

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

  return 0;
}
输出【Output】

myvector contains: 4 5 7 8 9 10

删除元素【Erase elements】

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

从向量中移除单个元素(位置)或一系列元素(第一、最后)。

This effectively reduces the container size by the number of elements removed, which are destroyed.

这有效地减少了容器的大小,减少了被移除的元素的数量,这些元素会被销毁。

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

因为向量使用数组作为其底层存储,所以删除向量端以外位置的元素会导致容器在段删除后将所有元素重新定位到它们的新位置。与其他类型的序列容器(如list或forward_list)对同一操作执行的操作相比,这通常是一种效率低下的操作。

swap

交换内容(公共成员功能)

实例【Example】
// swap vectors
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> foo (3,100);   // three ints with a value of 100
  std::vector<int> bar (5,200);   // five ints with a value of 200

  foo.swap(bar);

  std::cout << "foo contains:";
  for (unsigned i=0; i<foo.size(); i++)
    std::cout << ' ' << foo[i];
  std::cout << '\n';

  std::cout << "bar contains:";
  for (unsigned i=0; i<bar.size(); i++)
    std::cout << ' ' << bar[i];
  std::cout << '\n';

  return 0;
}
输出【Output】

foo contains: 200 200 200 200 200

bar contains: 100 100 100

交换内容【Swap content】

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

通过x的内容交换容器的内容,x是同一类型的另一个向量对象。大小可能不同。

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

在调用这个成员函数之后,这个容器中的元素是调用之前在x中的元素,而x的元素是在这个容器中的元素。所有迭代器、引用和指针对于交换的对象仍然有效。

Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.

请注意,存在一个同名的非成员函数swap,该函数使用类似于此成员函数的优化重载该算法。

clear

清除内容(公共成员函数)

实例【Example】
// clearing vectors
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  myvector.push_back (100);
  myvector.push_back (200);
  myvector.push_back (300);

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

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

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

  return 0;
}
输出【Output】

myvector contains: 100 200 300

myvector contains: 1101 2202

【Clear content】

Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.

移除向量中的所有元素(已销毁),使容器的大小为0。

A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:

不保证会发生重新分配,也不保证由于调用此函数而改变向量容量。强制重新分配的典型替代方案是使用交换:

emplace 

构造和插入元素(公共成员函数)

实例【Example】
// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}
输出【Output】

myvector contains: 10 200 100 20 30 300

构造并插入元素【Construct and insert element】

The container is extended by inserting a new element at position. This new element is constructed in place using args as the arguments for its construction.

通过在位置插入新元素来扩展容器。这个新元素是使用args作为构造参数就地构造的。

This effectively increases the container size by one.

这有效地将容器大小增加了一个。

An automatic reallocation of the allocated storage space happens if -and only if- the new vector size surpasses the current vector capacity.

当且仅当新向量大小超过当前向量容量时,才会自动重新分配分配分配的存储空间。

Because vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to shift all the elements that were after position by one to their new positions. This is generally an inefficient operation compared to the one performed by other kinds of sequence containers (such as list or forward_list). See emplace_back for a member function that extends the container directly at the end.

因为向量使用数组作为它们的底层存储,所以在向量末端以外的位置插入元素会导致容器将位置后面的所有元素逐个移动到它们的新位置。与其他类型的序列容器(例如list或forward_list)执行的操作相比,这通常是一种低效的操作。请参见emplace_back,了解直接在末尾扩展容器的成员函数。

The element is constructed in-place by calling allocator_traits::construct with args forwarded.

通过调用分配器_traits::construct并转发args,可以就地构造元素。

A similar member function exists, insert, which either copies or moves existing objects into the container.

还有一个类似的成员函数insert,它可以将现有对象复制或移动到容器中。

emplace_back 

在末尾构造并插入元素(公共成员函数)

实例【Example】
// vector::emplace_back
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  myvector.emplace_back (100);
  myvector.emplace_back (200);

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}
输出【Output】

myvector contains: 10 20 30 100 200

在末尾构造并插入元素【Construct and insert element at the end】

Inserts a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its constructor.

在向量的末尾插入新元素,就在其当前的最后一个元素之后。这个新元素是使用args作为构造函数的参数就地构造的。

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

这将有效地将容器大小增加1,这将导致在新向量大小超过当前向量容量时(且仅当新向量大小超过当前向量容量时)自动重新分配分配分配的存储空间。

The element is constructed in-place by calling allocator_traits::construct with args forwarded.

通过调用分配器_traits::construct并转发args,可以就地构造元素。

A similar member function exists, push_back, which either copies or moves an existing object into the container.

存在一个类似的成员函数push_back,它将现有对象复制或移动到容器中。

Allocator:

get_allocator

获取分配器(公共成员函数)

实例【Example】
// vector::get_allocator
#include <iostream>
#include <vector>

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

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

  // construct values in-place on the array:
  for (i=0; i<5; i++) myvector.get_allocator().construct(&p[i],i);

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

  // destroy and deallocate:
  for (i=0; i<5; i++) myvector.get_allocator().destroy(&p[i]);
  myvector.get_allocator().deallocate(p,5);

  return 0;
}
输出【Output】

The allocated array contains: 0 1 2 3 4

获取分配器【Get allocator】

Returns a copy of the allocator object associated with the vector.

返回与向量关联的分配器对象的副本。

C++ 文章被收录于专栏

参考 C++ Reference

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务