我正在阅读加速C ++,我对下面发布的问题提出的建议很少。
这段代码有什么作用?
vector<int>u(10,100)
vector<int>v;
copy(u.begin(), u.end(), v.end());
提供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
std::copy()
不会更改迭代器的值std::copy()
的参数不依赖于特定容器,因此代码可以与不同的容器一起使用std::back_inserter()
仅适用于顺序容器,因此不能与地图一起使用std::copy()
的第三个参数不会导致编译器错误,但程序可能会有不同的行为insert()
w.insert(w.end(), u.begin(), u.end() );
insert()
可与大多数容器一起使用想不到任何。
push_back()
for ( std::vector<int>::const_iterator it = w.begin(); it != w.end(); ++it )
{
x.push_back( *it );
}
不能想到任何事情。
std::copy()
或vector::insert()
相比较慢。我的方法是否正确?还有哪些其他可能的解决方案?
答案 0 :(得分:5)
您的标题表明您对复制矢量感兴趣,但您的代码表明您有兴趣插入矢量(请记住,尽管其名称std::copy
用于插入此处)。< / p>
如果要复制:
// 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());
如果要插入,那么您描述的两种方法(使用std::copy
加上迭代器适配器或调用insert
成员)都是合适的。您应该根据您在特定代码点中使用容器还是使用迭代器来选择一个。 (当使用迭代器时,使用迭代器适配器的负担放在传递迭代器的客户端上,因此不必担心push_back
。)如果你只有迭代器,那么调用例如: insert
根本不是一个选择;如果你有容器,其中一个成员可以完成这项工作,那么随时可以使用它。我不会考虑使用算法的错误。
尝试将显式循环作为最后的选择。
答案 1 :(得分:0)
在我看来,作者的意思是仍然应该使用std :: copy()。所以第一个解决方案是(正如你的建议):
std::copy(u.begin(), u.end(), back_inserter(v));
另一个可能是:
v.resize(u.size());
std::copy( u.begin(), u.end(), v.begin() );