[英]Why am I getting std::out_of_range error?
I'm trying to make a function that reorders the elements of a vector if it is not in ascending order. 我正在尝试制作一个功能,如果不按升序排列,则可以对向量的元素进行重新排序。 I wrote this but when I compile it I get:
我写了这个,但是当我编译它的时候得到了:
terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check
抛出'std :: out_of_range'what()的实例后调用终止终止what():vector :: _ M_range_check
Could someone tell me what is wrong with my function? 有人可以告诉我我的功能出了什么问题吗? Thanks.
谢谢。
void reorder(vector<double>& orderA)
{
for (unsigned int i = 0; i < orderAngle.size(); ++i)
{
temp = orderA.at(i);
orderA.at(i) = orderA.at(i+1);
orderA.at(i+1) = temp;
}
return;
}
1- As mentioned in the comments by Olzhas, your code will go out of range when i becomes equal to orderAngle.size(), so you need to change your for loop to: 1-如Olzhas的评论中所述,当我等于orderAngle.size()时,您的代码将超出范围,因此您需要将for循环更改为:
for(unsigned int i = 0; i < orderAngle.size() - 1; ++i)
2- Your algorithm doesn't achieve what you want to achieve. 2-您的算法无法实现您想要的目标。
3- Do you really need to write your own algorithm to sort a vector of doubles? 3-您是否真的需要编写自己的算法来对双精度向量进行排序? How about using something like the following code:
如何使用类似以下代码的内容:
sort(vec.begin(), vec.end(), [](double x, double y) {
return (x < y);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.