vector<unique_ptr<>>赋值给vector<unique_ptr<>>
最后更新于:2022-04-01 06:44:15
##实战c++中的vector系列--vector<unique_ptr<>>赋值给vector<unique_ptr<>>
之前博客讲到 vector可以使用insert方法,将一个vector copy到另一个vector的后面。
之前的博客也讲到过,如果vector容器内部放的是unique_ptr是需要进行所有权转移的。
现在就来八一八如何`vector<unique_ptr<>> insert to vector<unique_ptr<>>`
如果常规的vector,我们就可以这么使用insert:
~~~
// inserting into a vector
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (3,100);//100 100 100
std::vector<int>::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<int> 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;
std::cout << '\n';
return 0;
}
//输出:
501 502 503 300 300 400 400 200 100 100 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 <iostream> // std::cout
#include <iterator> // std::make_move_iterator
#include <vector> // std::vector
#include <string> // std::string
#include <algorithm> // std::copy
int main () {
std::vector<std::string> foo (3);
std::vector<std::string> 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<iostream>
#include<vector>
#include <memory>
using namespace std;
void display_vector(vector<unique_ptr<int>> &vec);
int main()
{
vector<unique_ptr<int>> vec;
unique_ptr<int> s1(new int(1));
unique_ptr<int> s2(new int(2));
unique_ptr<int> s3(new int(3));
unique_ptr<int> 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<int> s5(new int(5));
vector<unique_ptr<int>> 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<unique_ptr<int>> &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
~~~