之前博客《實戰c++中的vector系列–構造、operator=和assign區別》寫了關於assign()方法,其中有一條就是:
replacing its current contents
modifying its size accordingly
就是替換了vector中已經存在的元素。
這裡就不再說明assign了。
push_back故名意思就是在vector末尾追加:
void push_back (const value_type& val);
void push_back (value_type&& val);
uses push_back to add a new element to the vector
具體使用就不寫代碼了,就是每一次push_back只能加入一個元素。
剩下的就是insert:
single element (1)
iterator insert (const_iterator position, const value_type& val);
fill (2)
iterator insert (const_iterator position, size_type n, const value_type& val);
range (3)
template
iterator insert (const_iterator position, InputIterator first, InputIterator last);
move (4)
iterator insert (const_iterator position, value_type&& val);
initializer list (5)
iterator insert (const_iterator position, initializer_list il);
實際應用:
// inserting into a vector
#include
#include
int main ()
{
std::vector myvector (3,100);
std::vector::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 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;="" '\n';="" return="" 0;="" }="" 輸出:="" myvector="" contains:="" 501="" 502="" 503="" 300="" 400="" 200="" 100="" 100
assign vs insert
只有當vector為空的時候,assign和insert是相同的。
如果vetor是空的,使用assign更好。