📜  C++ Vector

📅  最后修改于: 2020-10-21 02:25:51             🧑  作者: Mango

C++ Vector

Vector是实现动态数组的序列容器类,这意味着在附加元素时大小会自动更改。Vector可将元素存储在连续的内存位置中,并在运行时根据需要分配内存。

向量和数组之间的区别

数组遵循静态方法,这意味着在运行时不能更改其大小,而vector实现动态数组意味着在添加元素时会自动调整其大小。

句法

考虑向量’v1’。语法为:

vector v1;

让我们看一个简单的例子。

#include
#include
using namespace std;
int main()
{
vector v1;
v1.push_back("javaTpoint ");
v1.push_back("tutorial");
for(vector::iterator itr=v1.begin();itr!=v1.end();++itr)
cout<<*itr;
return 0; 
}

输出:

javaTpoint tutorial

在此示例中,矢量类已用于显示字符串。

C++向量函数

Function Description
at() It provides a reference to an element.
back() It gives a reference to the last element.
front() It gives a reference to the first element.
swap() It exchanges the elements between two vectors.
push_back() It adds a new element at the end.
pop_back() It removes a last element from the vector.
empty() It determines whether the vector is empty or not.
insert() It inserts new element at the specified position.
erase() It deletes the specified element.
resize() It modifies the size of the vector.
clear() It removes all the elements from the vector.
size() It determines a number of elements in the vector.
capacity() It determines the current capacity of the vector.
assign() It assigns new values to the vector.
operator=() It assigns new values to the vector container.
operator[]() It access a specified element.
end() It refers to the past-lats-element in the vector.
emplace() It inserts a new element just before the position pos.
emplace_back() It inserts a new element at the end.
rend() It points the element preceding the first element of the vector.
rbegin() It points the last element of the vector.
begin() It points the first element of the vector.
max_size() It determines the maximum size that vector can hold.
cend() It refers to the past-last-element in the vector.
cbegin() It refers to the first element of the vector.
crbegin() It refers to the last character of the vector.
crend() It refers to the element preceding the first element of the vector.
data() It writes the data of the vector into an array.
shrink_to_fit() It reduces the capacity and makes it equal to the size of the vector.