我試圖訪問使用key
的std::map
數據,但我得到的錯誤錯誤:'operator []'不匹配?
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;
}
您使用'using namespace std',然後調用變量'pair'和'map'。你不應該這樣做,因爲名字衝突。 – apriori
澄清:這很有效,顯然。但是在第一個基於範圍的'for'循環範圍內使用'map'定義一個'std :: map'變量將導致不必要的衝突。在我看來,最好的做法是,在使用'using namespace X;'(或者根本不使用'namespace X;')時,不要將名稱空間X中的類型名稱用作變量名稱。 – apriori