复制/插入向量 我正在阅读C++加速,我对下面的问题提出了一些建议。

复制/插入向量 我正在阅读C++加速,我对下面的问题提出了一些建议。,c++,vector,insert,copy,C++,Vector,Insert,Copy,这个代码是做什么的 vector<int>u(10,100) vector<int>v; copy(u.begin(), u.end(), v.end()); 优势 std::copy()不会更改迭代器的值 由于std::copy()的参数不依赖于特定的容器,因此代码可以在不同的容器中重用 缺点 std::back\u inserter()仅适用于顺序容器,因此不能用于映射 将错误的迭代器值赋给std::copy()的第三个参数不会导致编译器错误,

这个代码是做什么的

vector<int>u(10,100)    
vector<int>v;    
copy(u.begin(), u.end(), v.end());
优势
  • std::copy()
    不会更改迭代器的值
  • 由于
    std::copy()
    的参数不依赖于特定的容器,因此代码可以在不同的容器中重用
缺点
  • std::back\u inserter()
    仅适用于顺序容器,因此不能用于映射
  • 将错误的迭代器值赋给
    std::copy()
    的第三个参数不会导致编译器错误,但程序的行为可能不同

insert()
优势
  • insert()
    可用于大多数容器
缺点 想不出有什么


向后推()
for(std::vector::const_迭代器it=w.begin();it!=w.end();++it)
{
x、 推回(*它);
}
优势 我想不出有什么

缺点
  • 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());
//这要求向量类型完全匹配
std::向量v=u;
//如果向量的值不同_类型
//这要求源的值类型为
//可转换为目标的值类型
向量v(u.begin(),u.end());
如果您想要插入,那么您描述的两种方法(使用
std::copy
加上迭代器适配器或调用
insert
成员)都是合适的。您应该根据在特定代码点中使用容器还是迭代器来选择一个。(在使用迭代器时,使用迭代器适配器的负担是由传递迭代器的客户端承担的,因此无需担心
推回
)如果您只有迭代器,那么调用例如
插入
就不是一个选项;如果您确实拥有容器,并且其中一个成员可以完成该工作,那么您可以随意使用它。我不会考虑使用一个算法的错误。


在我看来,作者的意思是仍然应该使用std::copy()。因此,第一个解决方案是(如您所建议的):

另一个可能是:

v.resize(u.size());
std::copy( u.begin(), u.end(), v.begin() );

在所有情况下,您都忘记了
dest.reserve(src.size()):)虽然
dest.insert(…)
很可能通过
src_end-src_begin
在内部执行此操作,但最好事先执行此操作,因为无法保证(而且您手头有大小)。@xeo,感谢您提供此信息。您对我所采用的adv和disadv方法有何看法?@Xeo——除非使用专门的自定义分配器或重复分析的数据,否则我很少认为需要使用
保留
容量
。,使用普通迭代器调整大小和复制
v=u
有什么问题?还有一个复制构造函数可以用来代替赋值运算符:
std::vector v(u)。这种方式是在构造
v
时复制
u
,其中赋值运算符在构造
v
时复制
u
。@Helstein不涉及赋值运算符。
for ( std::vector<int>::const_iterator it = w.begin(); it != w.end(); ++it )
{
    x.push_back( *it );
}
// 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(u.begin(), u.end(), back_inserter(v));
v.resize(u.size());
std::copy( u.begin(), u.end(), v.begin() );