简体   繁体   English

旋转矢量元素的值大于矢量大小?

[英]Rotating vector elements by value greater than vector size?

Somewhat of a simple question, I'm rotating the order of elements in a vector using std::rotate: 一个简单的问题,我正在使用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? 我遇到了一个分段错误,其中K> = V.size(),我正在努力理解:1)为什么会发生此错误? and 2) how I can perform a rotate operation with such a K value? 和2)如何使用这样的K值执行旋转操作?

For example, a K of 6 should output {2,3,4,1} 例如,K为6时应输出{2,3,4,1}

If K is greater than V.size() , then V.rbegin()+K is an invalid iterator. 如果K大于V.size() ,则V.rbegin()+K是无效的迭代器。 You need to reduce K by mod size. 您需要通过mod大小减少K。 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. 请注意首先测试size != 0否则将被零除。

V.rebegin() + 6 is not a valid iterator. V.rebegin() + 6不是有效的迭代器。 Which element would it point to? 它指向哪个元素? I will assume you want to rotate the vector by K elements. 我假设您想将向量旋转K个元素。 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}. 我不确定为什么您期望K为6会导致{2,3,4,1},它得到{3,4,1,2}。 Perhaps I've misunderstood the question. 也许我误解了这个问题。

Edit: See this answer about checking the size first. 编辑:请参阅此答案有关首先检查大小。

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

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