C++ 映射插入不良行为

标签 c++ dictionary insert

考虑以下代码:

// in global space 
int v[50000];

// in a function
int n;
std::cin >> n;
for(int i(0); i < n; ++i)
    std::cin >> v[i];

std::map<int, int, std::greater<int>> m;
for(int i(n-1); i > -1; --i){
    auto it(m.find(m[v[i]]));
    if(it == std::end(m)){
            m[v[i]] = i; // (1)
            // m.insert({m[v[i]], i}); (2)
            // m.insert(std::make_pair(m[v[i]], i)); (3)
    }
}
std::cout << "map : \n";
for(auto &x: m)
    std::cout << x.first << ' ' << x.second << '\n';

假设我们有输入:3 1 2 3 使用第一个版本的 map 插入我得到了预期的结果:

3 2

2 1

1 0

但是我得到了第二个和第三个:

3 0

2 0

1 0

他们应该给出相同的结果..

最佳答案

m.insert({m[v[i]], i}); //(2)

您必须按如下方式更正它:

m.insert({v[i], i}); //(2)

关于C++ 映射插入不良行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30398644/

相关文章:

c++ - OpenCV - OpenCV Mat 等效于 boost 矩阵 array_type

c++ - 如何更改 cv::Mat 中所有像素的值

python - 如何使用python从文件中打印字典的值

Python将具有多个键的Dict转换为Dataframe

c# - 如何访问字典中唯一的 KeyValuePair?

c++ - 为什么 CWE 认为 rand() 具有潜在危险

c++ - 文件是否需要扩展名才能在 C/C++ 中使用 open() 打开?

.net - 使用 dapper 插入一对多实体

python - 在每个第 n 个元素之后插入 Python 列表中的元素

php - SQL:插入所有字段或多个查询的 1 个查询?