English 中文(简体)
我如何扭转C++的病媒?
原标题:How do I reverse a C++ vector?

在C++中是否有内在病媒功能来扭转病媒的形成?

或者,你只是需要人工做吗?

最佳回答

<代码>std:reverse in algorithm 为此的负责人。

#include <vector>
#include <algorithm>

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

所有集装箱都提供其含量的view>,rbegin(rend(>>。 这两项职能交还了反转器,可像正常功能一样使用,但将像集装箱一样看待。

#include <vector>
#include <iostream>

template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "
"){
  --last;
  for(; first != last; ++first){
    std::cout << *first << delim;
  }
  std::cout << *first;
}

int main(){
  int a[] = { 1, 2, 3, 4, 5 };
  std::vector<int> v(a, a+5);
  print_range(v.begin(), v.end(), "->");
  std::cout << "
=============
";
  print_range(v.rbegin(), v.rend(), "<-");
}

,Ideone。 产出:

1->2->3->4->5
=============
5<-4<-3<-2<-1

页: 1 ......

std::reverse(str.begin(), str.end());

通常,你想要扭转病媒的原因是,你通过把所有项目推向尾来加以填充,但实际上却以相反的方式接收这些物品。 在这种情况下,你可以通过使用<条码>dque<>/条码”来扭转集装箱状况,直接将其推向前线。 (您可在前面加上<代码>查询器:insert(<>>>/code>,但是,如果存在大量物品,则会很慢,因为它必须把所有其他物品放在每一处插入。) 而不是:

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




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?