之前博客講到 vector可以使用insert方法,將一個vector copy到另一個vector的後面。
之前的博客也講到過,如果vector容器內部放的是unique_ptr是需要進行所有權轉移的。
現在就來八一八如何vector
如果常規的vector,我們就可以這麼使用insert:
// inserting into a vector
#include
#include
int main ()
{
std::vector myvector (3,100);//100 100 100
std::vector::iterator it;
it = myvector.begin();
it = myvector.insert ( it , 200 );//200 100 100 100
myvector.insert (it,2,300);//300 300 200 100 100 100
// "it" no longer valid, get a new one:
it = myvector.begin();
std::vector anothervector (2,400);
myvector.insert (it+2,anothervector.begin(),anothervector.end());
//now, 300 300 400 400 200 100 100 100
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;="" }="" 輸出:="" 501="" 502="" 503="" 300="" 400="" 200="" 100=""
但是對於vector內的unique point來說,就不能簡單的使用普通迭代器了:需要使用對迭代器就行std::make_move_iterator操作:
看下英文描述最可靠:
A move_iterator is an iterator adaptor that adapts an iterator (it) so that dereferencing it produces rvalue references (as if std::move was applied), while all other operations behave the same.
就跟我們之前用到的std::move作用是一樣一樣的~
看看使用例子:
#include // std::cout
#include // std::make_move_iterator
#include // std::vector
#include // std::string
#include // std::copy
int main () {
std::vector foo (3);
std::vector bar {"one","two","three"};
std::copy ( make_move_iterator(bar.begin()),
make_move_iterator(bar.end()),
foo.begin() );
// bar now contains unspecified values; clear it:
bar.clear();
std::cout << "foo:";
for (std::string& x : foo) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
//輸出:
foo: one two three
接下來就是我們的使用了,簡單了吧:
#include
#include
#include
using namespace std;
void display_vector(vector> &vec);
int main()
{
vector> vec;
unique_ptr s1(new int(1));
unique_ptr s2(new int(2));
unique_ptr s3(new int(3));
unique_ptr s4(new int(4));
vec.push_back(std::move(s1));
vec.push_back(std::move(s2));
vec.push_back(std::move(s3));
vec.push_back(std::move(s4));
unique_ptr s5(new int(5));
vector> des_vec;
des_vec.push_back(std::move(s5));
des_vec.insert(des_vec.end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()));
display_vector(des_vec);
cout << "now, des_vec size: " << des_vec.size() << endl;
cout << "now, vec size: " << vec.size() << endl;
return 0;
}
void display_vector(vector> &vec)
{
for (auto it = vec.begin(); it != vec.end(); it++)
{
cout << **it << endl;
}
//輸出結果:
5
1
2
3
4
now, des_vec size: 5
now, vec size: 4