c++ - 代码的后半部分以某种方式影响前一部分

标签 c++ c++11

我有这个程序:

#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/

相关文章:

c++ - 为其他容器实现 std::rank

c++ - 为什么要使用 std::forward?

c++ - 按值返回常量和非常量

c++ - 无法将 Map 声明和分配为 const

c++11 - 类型选择中的 C++ 模板元编程问题

c++ - 如何修复变量声明和全局构造函数警告?

c++ - 传递额外的 wParam/lParam 参数?

c++ - 使用 c++ eigen 库的未知错误

c++ - 有没有办法将 lambda 的签名推断为 mpl 序列?

c++ - 将字符 vector 转换为字符串的最快方法