如何使用迭代器初始化地图的键字段?


#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 不起作用),但第二个字段确实有效?解决方案是什么?

为什么我不能初始化地图的键字段(it->first=s 不 工作),但第二个字段确实有效?。解决方案是什么?

你的问题本身就有答案。std::map将键映射到值。这意味着,在创建本身时,您需要同时设置(键和值)。

it->first=s;这不会编译,因为你没有提到,密钥是什么。

it->second=s;这是一个 UB。既然你还没有提到它的钥匙。

std::map 是一个包含键值的排序关联容器 与唯一键配对。键使用比较进行排序 函数比较。

因此,为了进行比较并在数据结构中放置正确的位置,它需要同时提供这两个信息。

解决方案是:

  • mapa[key] = value;使用(operator[]).您可以使用它通过相应的键直接访问映射中的值。
  • 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"));

最新更新