【问题标题】:Can I return a vector to extend an existing vector with C++11? [duplicate]我可以返回一个向量以使用 C++11 扩展现有向量吗? [复制]
【发布时间】:2013-07-11 16:11:15
【问题描述】:

用函数返回的向量的内容扩展向量的最佳方法是什么?

我能做到:

std::vector<int> base;
{
    std::vector<int> tmp = getVec(); //RVO will make this efficient
    base.reserve(base.size() + tmp.size());
    base.insert(base.end(), std::make_move_iterator(tmp.begin()), std::make_move_iterator(tmp.end()));
}

但是是否可以在不创建 tmp 的情况下做到这一点?我可以通过引用将 base 传递给 getVec,但我觉得参数应该用于输入,返回值用于输出。理想情况下,我能做到:

base.extend(getVec());

但我看不出如何使用法线向量函数来做到这一点。

【问题讨论】:

  • append(base, getVec());,它有适当的身体来做移动和东西。基本上,将临时 std::vector 从局部变量移动到参数。

标签: c++ performance c++11 coding-style


【解决方案1】:

将要附加的向量作为参数发送。这被广泛使用和接受。

void func(vector<int>* master) {
   // Generate values as you did in getVec() but now append to the original vector
   // instead of to a temp. 
   while(generatingNumbers(i))
       master->push_back(i);
}

【讨论】:

  • 这不是 C++,是 C。如果有引用,为什么还要指针?而这种类型的功能不是做这种事情的正确方法。在 OP 的问题上查看 @Xeo 的评论。那是好办法。编译器使用移动语义。
猜你喜欢
  • 2019-11-13
  • 2017-02-14
  • 2010-09-23
  • 2011-01-20
  • 2019-06-27
  • 1970-01-01
  • 2015-01-31
  • 2012-10-08
  • 2014-08-02
相关资源
最近更新 更多