2016-04-24 183 views
-1

此代碼假設打印在開始和結束之間的一定範圍內丟棄的學生ID,當我運行它的程序崩潰..任何建議? 輸入是編號[12001,12002,12003,12006] 期望的輸出的陣列:12004,12005點//滴下的ID 12001和12006問題For循環C++

void dropped_students(vector<string> students_id){ 
    // creating array of numbers between max and min 
    int start = min_id(students_id) , end = max_id(students_id); 
    vector<int> numbers; 
    string diff_number; 
    for (int i = start ; i <= end ; i++) 
     numbers.push_back(i); 
    // finding the drooped numbers 
    for (int i = 0 ; i < numbers.size(); i++){ 
     int found = 0; 
     int num = atof(students_id[i].c_str()); 
     for (int j = 0 ; j < students_id.size() ; j++){ 
      int stu_id = atof(students_id[j].c_str()); 
      if (stu_id == num) 
       found = 1;break; 
     } 
     if (found == 0) 
      {cout<< num << endl;} 
    }  
} 
+4

「有什麼建議? 「您應該發佈一個[最小化,完整和可驗證的示例](http://stackoverflow.com/help/mcve)並描述所需的行爲以在此處發佈問題。 – MikeCAT

+0

您的代碼格式不正確。而且您還沒有表達過您的預期輸出以及您卡在哪裏。 – Tejendra

回答

0

之間你在「數字」更多的項目比「studends」,但是你使用「students_id [i]」,其中「i」是「數字」內的索引=>這超出了範圍。

我覺得這條線

int num = atof(students_id[i].c_str()); 

應該

int num = numbers[i]; 
0

我會做它用這種方式來優化功能:通過學生證的數值

  1. 排序數組
  2. 掃描學生數組,找到差距並輸出它們

功能可能看起來像下面這樣:

#include <algorithm> 

bool CompareIDs(string students_id1, string students_id2) { 
    return atoi(students_id1.c_str()) < atoi(students_id2.c_str()); 
} 

void dropped_students(vector<string> students_id){ 
    // creating array of numbers between max and min 
    sort(students_id.begin(), students_id.end(), CompareIDs); 
    bool first = true; 
    int last; 
    for (auto strid : students_id) { 
     int id = atoi(strid.c_str()); 
     if (!first) { 
      if (id>last+1) 
      for (int i = last + 1; i < id; i++) 
       cout << i << endl; 
     } 
     last = id; 
     first = false; 
    } 
} 

我這個主要功能進行了測試:

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    vector<string> students_id; 
    students_id.push_back("12001"); 
    students_id.push_back("12002"); 
    students_id.push_back("12003"); 
    students_id.push_back("12006"); 
    dropped_students(students_id); 
} 

和它印:

12004 
12005