gpt4 book ai didi

c++ - 如何使用迭代器初始化映射的关键字段?

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:31 25 4
gpt4 key购买 nike

#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;
}

为什么我无法初始化 map 的关键字段(it->first=s 不起作用)但第二个字段却起作用?。解决方案是什么?

最佳答案

Why can I not initialize the key field of a map (it->first=s does not work) but the second field does work?. And what is the solution?

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

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

it->second=s;这是一个UB。因为您没有提到 key 。

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare.

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

解决方案是:

  • 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"));

关于c++ - 如何使用迭代器初始化映射的关键字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com