unordered_map <int, std::vector<double>> 中的段错误

Seg fault in unordered_map <int, std::vector<double>>

(分段错误)访问与无序映射中的键关联的值时发生错误。有什么地方我犯了错误吗?

以下代码片段中的分段错误:

void read_mdl(const std::string& fname) {
        std::ifstream f(fname);

        std::unordered_map<int, std::vector<double>> pt_;

        while(f) {
            int xi = -1;
            int pa = 0;
            double score = -1;
            f >> xi >> pa >> score;
            if(xi == -1) { break; }

            std::unordered_map<int, std::vector<double>>::iterator it = pt_.find(pa);

            std::cout << xi << " " << pa << " " << score << std::endl;

            if (it != pt_.end()) {
                // Update from @Matthias247
                 auto a = pt_.insert(std::make_pair(pa, std::vector<double>(n_, 0)));
                 it = a.first;
            }

            (it->second)[xi] = score; // causing segmentation fault
        }
    }

如果找不到元素,您的迭代器就会损坏。在这种情况下,您使用 pt_.insert 插入一个新元素,但不要更改迭代器。之后访问它会导致段错误。如果 insert returns 一个迭代器并将其分配给 it.

,则执行新查找或查找

更新:

如果我正确理解 insert API 它应该像

if (it != pt_.end()) {
    auto a = pt_.insert(std::make_pair(pa, std::vector<double>(n_, 0)));
    it = a.first;
}

(it->second)[xi] = score;

发现错误。

是key是否存在检查错误

关于我的片段:

if (it != pt_.end()) // incorrect way

if (it == pt_.end()) // right way