2015-05-09 43 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]它將超過向量大小,如果您沒有檢查循環條件。

您的代碼有多個缺陷。輸出將與輸入相同,提示:知道傳遞引用和傳遞值之間的差異,然後檢查一些排序算法。