在C++中是否有一个内置的向量函数来反转向量?
或者你只需要手动完成?
发布于 2012-01-16 16:46:21
在algorithm
头中有一个用于此目的的函数std::reverse
。
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a;
std::reverse(a.begin(), a.end());
return 0;
}
发布于 2012-01-16 16:48:24
您可以像这样使用std::reverse
std::reverse(str.begin(), str.end());
发布于 2020-06-17 16:07:50
通常,您想要反转向量的原因是因为您通过在末尾推送所有项目来填充它,但实际上是以相反的顺序接收它们。在这种情况下,您可以通过使用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
https://stackoverflow.com/questions/8877448
复制相似问题