复制/插入矢量

时间:2012-08-31 16:25:17

标签: c++ vector insert copy

我正在阅读加速C ++,我对下面发布的问题提出的建议很少。

  1. 这段代码有什么作用?

    vector<int>u(10,100)    
    vector<int>v;    
    copy(u.begin(), u.end(), v.end());
    
  2. 提供2种纠正程序的方法,并列出其优缺点。

  3. 第一部分非常简单,但我在第二部分需要帮助。我提供了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()相比较慢。

    我的方法是否正确?还有哪些其他可能的解决方案?

2 个答案:

答案 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() );