For 循环 c++ 的问题
issue with For loop c++
这段代码假设在开始和结束之间的一定范围内打印掉落的学生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;}
}
}
你在"numbers"中的项目比在"studends"中有更多的项目,但是你使用"students_id[i]",其中"i"是"numbers"=>这超出了范围。
我认为这行
int num = atof(students_id[i].c_str());
应该是
int num = numbers[i];
我会以这种方式来优化您的函数:
- 按学生证的数值对数组进行排序
- 扫描学生阵列,定位差距并输出它们
该函数可能如下所示:
#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
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题