Somewhat of a simple question, I'm rotating the order of elements in a vector using std::rotate:
std::vector<int> V {1,2,3,4};
std::rotate(V.rbegin(), V.rbegin() + K, V.rend());
//output: {4,1,2,3}
I'm getting a segmentation fault where K is >= V.size(), and I'm struggling to understand: 1) why this error is occurring? and 2) how I can perform a rotate operation with such a K value?
For example, a K of 6 should output {2,3,4,1}
If K
is greater than V.size()
, then V.rbegin()+K
is an invalid iterator. You need to reduce K by mod size. Something like:
if (V.size() != 0) {
std::rotate(V.rbegin(), V.rbegin() + (K % V.size()), V.rend());
}
Note the test for size != 0
first - otherwise you'll get division by zero.
V.rebegin() + 6
is not a valid iterator. Which element would it point to? I will assume you want to rotate the vector by K elements. What you need to do is apply the modulo operator to find out which value should be at the front of the vector.
std::vector<int> V {1,2,3,4};
const auto K = 4 % V.size();
std::rotate(V.rbegin(), V.rbegin() + K, V.rend());
I'm not sure why you expect that K of 6 should result in {2,3,4,1}, it gives {3,4,1,2}. Perhaps I've misunderstood the question.
Edit: See this answer about checking the size first.
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.