如何反转 C 向量?

新手上路,请多包涵

C++ 中是否有内置的向量函数来反转向量?

还是您只需要手动完成?

原文由 Dollarslice 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 922
2 个回答

为此目的,在 algorithm 标头中有一个函数 std::reverse

 #include <vector>
#include <algorithm>

int main() {
  std::vector<int> a;
  std::reverse(a.begin(), a.end());
  return 0;
}

原文由 Ivaylo Strandjev 发布,翻译遵循 CC BY-SA 3.0 许可协议

通常,您想要反转向量的原因是因为您通过在最后推动所有项目来填充它,但实际上是以相反的顺序接收它们。在这种情况下,您可以使用 deque 来反转容器,然后将它们直接推到前面。 (或者您可以使用 vector::insert() 在前面插入项目,但是当有很多项目时,这会很慢,因为每次插入都必须将所有其他项目随机排列。)所以与:

 std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
    foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());

您可以改为:

 std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
    foo.push_front(nextItem);
}
// No reverse needed - already in correct order

原文由 Arthur Tacca 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题