#include <iostream>
#include <map>
#include <string>
int main ()
{
std::string s;
std::cout<<" String : ";
std::getline(std::cin,s);
std::map<std::string,std::string> mapa;
std::map<std::string,std::string>::iterator it(mapa.begin());
it->first = s;
it->second = s;
std::cout << it->second << std::endl;
return 0;
}
为什么我不能初始化映射的键字段(it-> first = s不起作用),但是第二个字段却起作用?解决方案是什么?
最佳答案
您的问题本身就有答案。 std::map
将键映射到值。这意味着,在创建本身时,您需要同时设置(键和值)。it->first=s;
不会编译,因为您没有提到,关键是什么。it->second=s;
这是一个UB。既然您没有提到它的 key 。
因此,为了进行比较并将其放置在数据结构中的正确位置,它需要同时使用这两个信息。
解决方案是:
使用mapa[key] = value;
的
(operator[])
。您可以使用它们通过相应的键直接访问 map 中的值。 mapa.emplace("key", "value");
mapa.insert ( std::pair<std::string, std::string>("key", "value") );
mapa.insert ( std::make_pair("key", "value") );
std::map<std::string,std::string>::iterator it(mapa.begin());
mapa.insert (it, std::pair<std::string, std::string>("key", "value"));