看程序的时候遇到了“向量后推函数”,功能没怎么看懂,查了下手册,做个功能普及。
void push_back (const value_type& val);
Add element at the end1
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.
这有效地将容器大小增加了一个,这会导致分配的存储空间自动重新分配,前提是(且仅当)新向量大小超过当前向量容量时。
搞些代码试试
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
int main()
{
char myfavorate[50] = "My favorite blog is:";
char blog[] = "lab_3D";
std::vector<char> myvector={ myfavorate ,myfavorate+21 };
std::cout << myfavorate <<"\n";
for (int i = 0;i < sizeof(blog);i++)
myvector.push_back(blog[i]);
for (int k = 0; k < myvector.size(); k++)
std::cout << myvector[k] ;
std::cout << "\n";
return 0;
}
输出结果:

本文深入解析了C++标准库中向量容器的后推(push_back)函数,阐述其功能为在向量的末尾添加一个新元素,并详细解释了元素的复制或移动过程,以及如何在达到向量容量上限时触发自动重新分配存储空间。通过具体代码示例展示了如何使用push_back函数将一个字符串逐字符添加到向量中。
421

被折叠的 条评论
为什么被折叠?



