sam*_*tha 3 c++ copy insert vector
我正在阅读Accelerated C++,我对下面发布的问题提出的建议很少.
这段代码有什么作用?
vector<int>u(10,100)
vector<int>v;
copy(u.begin(), u.end(), v.end());
Run Code Online (Sandbox Code Playgroud)提供2种可能的方法来纠正程序,并列出其优缺点.
第一部分非常简单,但我在第二部分需要帮助.我提供了3种方法,我想知道是否有更多可能的解决方案.
另外,我不确定我的方法的优点和缺点.我试过了,所以请告诉我你的意见.
copy()std::vector<int> u(10, 100);
std::vector<int> v;
std::vector<int> w ;
std::vector<int> x ;
std::copy(u.begin(), u.end(), back_inserter(v)); // 1st way of doing
Run Code Online (Sandbox Code Playgroud)
std::copy() 不会更改迭代器的值std::copy()不依赖于特定容器,因此代码可以与不同的容器一起使用std::back_inserter() 仅适用于顺序容器,因此不能与地图一起使用std::copy()不会导致编译器错误,但程序可能表现不同insert()w.insert(w.end(), u.begin(), u.end() );
Run Code Online (Sandbox Code Playgroud)
insert() 可与大多数容器一起使用想不到任何.
push_back()for ( std::vector<int>::const_iterator it = w.begin(); it != w.end(); ++it )
{
x.push_back( *it );
}
Run Code Online (Sandbox Code Playgroud)
不能想到任何.
std::copy()或相比较慢vector::insert().我的方法是否正确?还有哪些其他可能的解决方案?
你的标题表明你有兴趣复制一个向量,但你的代码表明你有兴趣插入一个向量(请记住,尽管它的名字std::copy用于插入).
如果你想复制:
// This requires the vector types to match exactly
std::vector<int> v = u;
// In case the vector differ in their value_type
// This requires that the value_type of the source be
// convertible to the value_type of the destination
std::vector<int> v(u.begin(), u.end());
Run Code Online (Sandbox Code Playgroud)
如果要插入,则所描述的两种方法(使用std::copy加上迭代器适配器或调用insert成员)都是合适的.您应该根据您在特定代码点中使用容器还是使用迭代器来选择一个.(当使用迭代器时,使用迭代器适配器的负担放在传递迭代器的客户端上,所以不必担心push_back.)如果你只有迭代器,那么调用eg insert根本就不是一个选项; 如果你有容器,其中一个成员可以完成这项工作,那么随时可以使用它.我不会考虑使用算法的错误.
尝试将显式循环留作最后的选择.