2015-05-09 117 views
0

我正在尝试制作一个程序,它接收来自用户的数字,然后重新排列从最小到最大的数字。我正在使用矢量(我刚刚了解到),它给我一个下标超出范围的错误。我无法找到什么代码的一部分给了我这个错误,所以希望有人对矢量和C博学++可以找到它:C++矢量下标超出范围错误1221

#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; 
    } 
} 

回答

2

修复这些行这样的:

// 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++中的索引是如何工作的。他们是零索引!这意味着如果你想要这个元素和前面的元素,你必须得到矢量的大小减1.因此,对于10个项目(大小为10)的矢量,在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! 
} 
0

矢量索引以0开头。索引将是0n-1,如果您使用num[i + 1]它将超过向量大小,如果您没有检查循环条件。

您的代码有多个缺陷。输出将与输入相同,提示:知道传递引用和传递值之间的差异,然后检查一些排序算法。