我正在尝试制作一个程序,从用户那里接收数字,然后将数字从小到大重新排列。我正在使用 vector (我刚刚了解到),它给了我一个下标超出范围的错误。我找不到代码的哪一部分给我这个错误,所以希望对 vector 和 c++ 有更多了解的人可以找到它:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void order(int a, int b);
void orderRev(int a, int b);
int main() {
vector<int> num;
bool going = true;
do {
cout << "\nEnter a number or type 'x' to order:" << endl;
string reply;
getline(cin, reply);
if (reply != "x") {
int a = atoi(reply.c_str());
num.push_back(a);
cout << "\nYou currently have " << num.size() << " numbers added." << endl;
}
else {
going = false;
}
} while (going);
for (int i = 0; i < num.size(); i++) {
order(num[i], num[i + 1]);
}
for (int i = num.size() - 1; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
cout << "\nThe number you entered in order from least to greatest are: " << endl;
for (int i = 0; i < num.size(); i++) {
cout << num[i] << " ";
}
void order(int a, int b) {
if (a > b) {
int c = b;
b = a;
a = c;
}
}
void orderRev(int a, int b) {
if (a < b) {
int c = b;
b = a;
a = c;
}
}
最佳答案
将这些行修改为:
// added the -1 as this will now go up to the 2nd to last element
// for `n`, and the last element for `n+1`
for (int i = 0; i < num.size() - 1; i++) {
order(num[i], num[i + 1]);
}
// changed the starting number to size -2 (for the same reasoning)
for (int i = num.size() - 2; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
为什么要这样?想想 C++ 中的索引是如何工作的。它们是零索引的!这意味着如果您既想要元素又想要它前面的元素,则必须达到 vector 的大小减 1。因此,对于包含 10 个项目(大小 10)的 vector ,在 i == 9 处您的代码将像这样工作:
for (int i = 0; i < num.size(); i++) {
// i = 9
order(num[9], num[9+1]);// index 10 does not exist! Hence, you really need to go up to num.size() - 1!
}
关于C++ vector 下标超出范围错误 1221,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136674/