如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?



新手问题,但我搜索了这个,找不到明确解决我的问题 - 如果这很明显,请道歉。

我定义了一张地图,如下所示:

map<int, string> testmap = {
{ 0, "a" },
{ 1, "b" },
{ 2, "c" }
}

但是,我需要使用另一个函数提供的uint64_t值从testmap中检索值。

当我testmap[my_uint64_t_value]时,它会返回一个空字符串,所以我认为这是因为它将my_uint64_t_value添加为并将设置为NULL.

如果我将映射类型设置为<uint64_t, string>,至少是我目前定义键的方式,这是相同的。

但是,有没有办法让我:

  1. uint64_t值转换为常规int
  2. 将映射定义为<uint64_t, string>,并且能够定义我的 键作为"正确"类型?

似乎int类型转换并不常见,这是应该避免的吗?

你得到一个空字符串的原因是 std::map::operator[] 返回对值的引用,当且仅当它存在时,否则它会执行插入。我怀疑你有后一种情况。

您需要使用 std::map::find 进行搜索。

uint64_t keyToFind =  1;
if (auto iter = testmap.find(keyToFind); iter != testmap.cend()) 
{
// do something
std::cout << "Found!n";
}
else { std::cout << "Not Found!n"; }

就像评论中提到的@Rene,从uint64_tint的转换可能会导致溢出。因此,将密钥设置为更大的类型(根据要求(将是一个好主意。

std::map<uint64_t, std::string> testmap;

如另一个答案所述,如果映射中不存在键,则 map 类的[]运算符将使用默认构造的值执行插入。

您可以先使用count方法确定密钥是否存在于映射中,然后再访问它。

if(testmap.count(keyToFind))
return testmap[keyToFind];
else
report_key_not_found();

另一种解决方案是使用at方法来访问值。如果密钥不存在,它将引发std::out_of_range异常,而不是插入新密钥。

相关内容

最新更新