简体   繁体   English

使用std :: reverse反转向量前几个元素的顺序

[英]Using std::reverse to reverse the order of the first few elements of a vector

If I have a 如果我有一个

vector<int> vec { 1, 2, 3, 4}

How to use 如何使用

std::reverse std :: reverse

to turn it into 把它变成

vec {2, 1, 3, 4} vec {2,1,3,4}

You can use reverse with iterators as arguments like this: 您可以将带有迭代器的reverse用作这样的参数:

vector<int> vec { 1, 2, 3, 4};
reverse(vec.begin(), vec.begin()+2);

You may take a look here 你可以看看这里

You don't need to use std::reverse for what is essentially a much simpler operation. 您实际上不需要使用std::reverse进行简单得多的操作。 If you want to just swap the first two elements, use: 如果只想交换前两个元素,请使用:

std::swap (vec[0], vec[1]);

If your desire is to swap elements in groups of two (leaving any odd one at the end alone), you can use something like: 如果您希望以两个为一交换元素(最后只剩下一个奇数),则可以使用以下方法:

for (int i = 0, lim = vec.size() - vec.size() % 2; i < lim; i += 2)
    std::swap (vec[i], vec[i+1]);

If you want to reverse a section of the vector that's more than two elements, that's where I'd be contemplating the use of std::reverse . 如果你想扭转这两个以上要素的载体的部分,这就是我会考虑使用std::reverse You could reverse sections of the vector vec containing {1, 2, 3, 4, 5} with calls like: 您可以通过以下调用反转向量vec包含{1, 2, 3, 4, 5}

std::reverse (vec.begin(),     vec.end()      ); // -> {5, 4, 3, 2, 1}
std::reverse (vec.begin(),     vec.begin() + 3); // -> {3, 2, 1, 4, 5}
std::reverse (vec.begin() + 1, vec.begin() + 4); // -> {1, 4, 3, 2, 5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM