我正在尝试将对象插入C ++中的 unordered_map 中。我找到了一种插入它的方法 map.insert(std :: make_pair(key,object))。但是,我不明白为什么我们应该使用配对而不是常规的 map [key] = value 。而且,我想知道如何从键中访问值。 地图[键] 不起作用。
答案 0 :(得分:2)
以下是将值放入无序映射的几种方法。
您会很抱歉,您问:)
值得一看cppreference.com上的参考资料,但一定要阅读有关该主题的最新书籍。像高级语言一样,c ++并不容易显而易见。
#include <unordered_map>
#include <string>
#include <cstring>
#include <tuple>
#include <iostream>
using MyMap = std::unordered_map<int, std::string>;
int main()
{
auto m = MyMap();
// only allowed if the mapped_type is default-constructible
m[0] = "zero";
// old-school way, with pair
m.insert(std::make_pair(1, "one"));
// "nicer" way with emplace
m.emplace(3, "three");
// ultra-technical way with piecewise_construct (useful for constructing complex objects without copy/move)
m.emplace(std::piecewise_construct, std::make_tuple(2), std::make_tuple("two"));
// another demonstration of piecewise_construct
const char* four = "four";
std::size_t four_len = std::strlen(four);
m.emplace(std::piecewise_construct,
std::make_tuple(2), // arguments for the key's constructor
std::make_tuple(four, four_len)); // arguments for the mapped-object's constructor
std::string five = "five";
auto ib = m.try_emplace(5, std::move(five));
if (std::get<bool>(ib))
{
// emplaced - five's contents are valid but unspecified as it has been moved-from
}
else
{
// not emplaced - five's contents are still defined to be "five"
}
// and now let's retrieve the items..
// this will only work if m is mutable and the mapped type is default-constructible.
auto& s_zero = m[0];
std::cout << s_zero << std::endl;
// map iterators point to pairs of const key, mapped_type
auto i_one = m.find(1);
if (i_one != std::end(m))
std::cout << i_one->second << std::endl;
// 'at' will throw if the key is not present
try
{
auto& i_two = m.at(2);
std::cout << i_two << std::endl;
}
catch(std::exception& e)
{
std::cerr << e.what() << std::endl;
}
auto exists = (m.count(3) != 0);
std::cout << "exists 3: " << exists << std::endl;
}