此代码假设在开始和结束之间的某个范围内打印已删除的学生ID,当我运行它时程序崩溃..任何建议? 输入是ID数组[12001,12002,12003,12006] 所需的输出:12004,12005 //在12001和12006之间删除的ID
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;}
}
}
答案 0 :(得分:0)
“数字”中的项目多于“studends”中的项目,但是您使用“students_id [i]”,其中“i”是“数字”中的索引=&gt;这超出范围。
我想这一行
int num = atof(students_id[i].c_str());
应该是
int num = numbers[i];
答案 1 :(得分:0)
我会这样做以优化你的功能:
该功能可能如下所示:
#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