error: no match for ‘operator[]’?

error: no match for ‘operator[]’?

我正在尝试使用 key 访问 std::map 数据,但出现错误

error: no match for ‘operator[]’ (operand types are ‘const std::pair’ and ‘int’)

#include <map>
#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<map<int, double>> mainData;
    for(int i = 0; i  < 10; i++) {
        map<int, double> data;
        data[1] = i;
        data[2] = i*2.0;
        data[5] = i*7.2;
        mainData.push_back(data);
    }
    for(auto& it1: mainData) {
        for(auto& it2: it1) {
            cout << it2.first  << "    " << it2.second << "\n";
            cout << it2[5] << "\n"; // Error occurs here
        }
        cout << "\n";
    }
    return 0;
}

也许您打算使用 it1[5]

我认为你这里有错字。我认为您打算访问 it1 而不是 it2,因为 it1 实际上是地图,而 it2 是地图中的对。

cout << it1[5] << "\n";

也许你应该使用不同的变量名:

#include <map>
#include <vector>
#include <iostream>

using namespace std;

int main() {
    vector<map<int, double>> mainData;
    for(int i = 0; i  < 10; i++) {
        map<int, double> data;
        data[1] = i;
        data[2] = i*2.0;
        data[5] = i*7.2;
        mainData.push_back(data);
    }
    for(auto& map: mainData) {
        for(auto& pair: map) {
            cout << pair.first  << "    " << pair.second << "\n";
            cout << map[5] << "\n";
        }
        cout << "\n";
    }
    return 0;
}

it2 是 std::pair (http://www.cplusplus.com/reference/utility/pair/)。你是认真的 1[5] 也许吧?实际做2[x]不行那是你写的代码有问题

因为标准对没有 [] 运算符,您可能指的是 it1[5] 而不是 it2[5]