之前說過了關於vector的insert()方法,把vector B的元素插入到vector A中,vector A中的結果我們可想而知,但是vector B中的元素還會如何?
看看之前寫過的程序:
#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
如果你看到此時,你肯定會在心裡罵娘,誰還關心vector B,並且vectorB並沒有變化。
現在是時候來點猛藥了,vector中放智能指針。
之前博客也講訴過對於vector的元素為智能指針的時候:
#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;
//display_vector(vec);
cout << "now, vec size: " << vec.size() << endl;
for (int i=0; i> &vec)
{
for (auto it = vec.begin(); it != vec.end(); it++)
{
cout << **it << endl;
}
}
上面代碼會崩潰,原因就是vec被insert後 ,vec變得無效了,我們不能對他做什麼。。。。。
但是需要明確的是這不是insert造成的,如果copy也會造成這一的結局,其實罪魁禍首就是make_move_iterator
再看程序:
#include
#include
#include
#include
#include
int main()
{
std::list s{ "one", "two", "three" };
std::vector v1(s.begin(), s.end()); // copy
std::vector v2(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end())); // move
std::cout << "v1 now holds: ";
for (auto str : v1)
std::cout << "\"" << str << "\" ";
std::cout << "\nv2 now holds: ";
for (auto str : v2)
std::cout << "\"" << str << "\" ";
std::cout << "\noriginal list now holds: ";
for (auto str : s)
std::cout << "\"" << str << "\" ";
std::cout << '\n';
}
//輸出:
//v1 now holds : "one" "two" "three"
//v2 now holds : "one" "two" "three"
//original list now holds : ""
最後再上一個官方程序:
#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;
}
* 需要注意:*
* bar.clear();*
因此此時: bar now contains unspecified values; clear it: