我正在尝试更新 an 的值std::pair,但这会导致编译器错误。如何解决这个问题?
#include <unordered_map>
#include <utility>
#include <string>
#include <iostream>
int main(int argc, char *argv[])
{
std::unordered_map<int, std::pair<std::string, std::string>> test1;
test1.insert(std::make_pair(1, std::make_pair("good1", "bad1")));
test1.insert(std::make_pair(2, std::make_pair("good2", "bad2")));
test1.insert(std::make_pair(3, std::make_pair("good3", "bad3")));
test1.insert(std::make_pair(4, std::make_pair("good4", "bad4")));
std::unordered_map<int, std::pair<std::string, std::string>>::const_iterator test2
= test1.find(1);
if (test2 == test1.end())
{
std::cout << "Could not find test2 in test1\n";
return 0;
}
std::cout << "First item is: " << test2->second.first << "...second item is: " << test2->second.second << "\n";
/* This line is throwing an error about "No operator '=' matches this operands. */
test2->second.second = "good";
std::cout << "First item is: " << test2->second.first << "...second item is: " << test2->second.second << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您正在使用const_iterator而不是iterator用于 test2:
std::unordered_map<int, std::pair<std::string, std::string>>::const_iterator test2 ...
Run Code Online (Sandbox Code Playgroud)
用:
std::unordered_map<int, std::pair<std::string, std::string>>::iterator test2 ...
Run Code Online (Sandbox Code Playgroud)
或使用auto以下方法简化它:
auto test2 = test1.find(1);
Run Code Online (Sandbox Code Playgroud)