push_back函数
语法:
1 |
void push_back(const value_type& __x); |
push_back() 在Vector最后添加一个元素
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// [23.2.4.3] modifiers /** * @brief Add data to the end of the %vector. * @param x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %vector and assigns the given data * to it. Due to the nature of a %vector this operation can be * done in constant time if the %vector has preallocated space * available. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { std::_Construct(this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; } else _M_insert_aux(end(), __x); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; vector<int> v2(10, 2); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); for(int i=0;i<v1.size();i++) cout<<v1[i]<<","; cout<<endl; } |
测试结果:
1 |
1,2,3,4,5, |