C++ 无法引用地图的键
C++ Can't reference key of the map
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
int main() {
int steps;
map<string, string> countries;
cin >> steps;
for (int i = 0; i < steps; ++i) {
string command;
cin >> command;
if(command == "CHANGE_CAPITAL") {
for(auto& s : countries) {
string& old_country = s.first;
string& old_capital = s.second;
}
}
}
}
您好!当我尝试编译此代码时,出现错误:
binding value of type 'basic_string<...>' to reference to type
'basic_string<...>' drops 'const' qualifier
对于字符串
string& old_country = s.first;
为什么会这样? (它不会为下一个字符串给出此错误 - 我通过引用评估 "s.second")。
编译器是 ISO C++ 1y (-std=c++1y)。
谢谢。
const string& old_country = s.first;
甚至更好:
const auto& old_country = s.first;
旁注:为了便于阅读,请为自动添加 const
。
你的地图对是:
std::pair<const std::string, string>
因为树的约束不能修改key。
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
int main() {
int steps;
map<string, string> countries;
cin >> steps;
for (int i = 0; i < steps; ++i) {
string command;
cin >> command;
if(command == "CHANGE_CAPITAL") {
for(auto& s : countries) {
string& old_country = s.first;
string& old_capital = s.second;
}
}
}
}
您好!当我尝试编译此代码时,出现错误:
binding value of type 'basic_string<...>' to reference to type 'basic_string<...>' drops 'const' qualifier
对于字符串
string& old_country = s.first;
为什么会这样? (它不会为下一个字符串给出此错误 - 我通过引用评估 "s.second")。
编译器是 ISO C++ 1y (-std=c++1y)。
谢谢。
const string& old_country = s.first;
甚至更好:
const auto& old_country = s.first;
旁注:为了便于阅读,请为自动添加 const
。
你的地图对是:
std::pair<const std::string, string>
因为树的约束不能修改key。