C++ map插入不需要的行为

zer*_*ght 2 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';
Run Code Online (Sandbox Code Playgroud)

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

3 2

2 1

1 0

然而,我得到了第二个和第三个:

3 0

2 0

1 0

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

Ste*_*hen 5

m.insert({m[v[i]], i}); //(2)
Run Code Online (Sandbox Code Playgroud)

您必须按如下方式更正:

m.insert({v[i], i}); //(2)
Run Code Online (Sandbox Code Playgroud)