简体   繁体   中英

Alternatives to std::reverse to reserve all elements in a vector?

std::vector<int> temp;
temp.insert(temp.begin(), points1.begin(), points1.end());
points1.clear();
std::vector<int> points1(temp.end(), temp.begin());
temp.clear();

I tried this but I've got an exception connects to memory allocation.

Use std::rbegin to iterate in the reverse order.

If you try points1(temp.end(), temp.begin()); , it starts from and illegal iterator (the end...).

Also, you're declaring points1 a second time in the code you provided

You can do this with one line of code. Construct a temporary vector using reverse iterators and then swap its contents back into the original vector.

// original vector
std::vector<int> points1;

// create temporary using reverse iterators and swap with original vector
std::vector<int>(points1.rbegin(), points1.rend()).swap(points1);

// unnamed temporary is destroyed automatically

Compiler Explorer demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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