我有这个程序:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <algorithm>
int main(int argc, const char * argv[]) {
std::vector<int> task_scores;
int n;
std::cin >> n;
for(int i = 0; i < n; i++) {
int sc;
std::cin >> sc;
task_scores.push_back(sc);
}
std::map<std::string, std::vector<size_t>> student_solutions;
std::string command = "";
while(true) {
std::vector<std::string> tok_com;
getline(std::cin, command);
std::stringstream strstream(command);
std::string token = "";
while (getline(strstream, token, ' ')) {
std::cout << token;
tok_com.push_back(token);
}
if (tok_com[0] == "SOLVED") {
std::string name = tok_com[1];
int task = std::stoi(tok_com[2]);
if(std::find(student_solutions[name].begin(), student_solutions[name].end(), task) !=
student_solutions[name].end()) {
student_solutions[name].push_back(task);
}
}
}
return 0;
}
如果您注释掉 if 子句,那么代码就可以正常工作。但是,如果您不这样做,代码将在尝试计算 token 时以 EXC_BAD_ACCESS
停止。怎么会这样?
最佳答案
But if you don't, the code stops with
EXC_BAD_ACCESS
when trying to cout the token. How can this happen?
if (tok_com[0] == "SOLVED") {
// ^^^
要求之前至少有一个值实际存储到循环中的 tok_com
vector 中。
在取消引用 tok_com
之前,您应该测试 tok_com.empty()
:
if (!tok_com.empty() && tok_com[0] == "SOLVED") {
// ^^^^^^^^^^^^^^^^^^^
// ...
}
您实际上遇到的是未定义的行为,包括冰箱爆炸、小恶魔从您的鼻孔中飞出,或者只是抛出异常您的调试环境或操作系统。
关于c++ - 代码的后半部分以某种方式影响前一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921033/