[英]How to return a value from std::map<int, std::string> with a uint64_t key type?
Novice question, but I searched for this and couldn't find something clearly solving my issue - apologies if this is obvious. 新手问题,但我进行了搜索,找不到明显解决我问题的方法-如果很明显,我们深表歉意。
I have defined a map which looks like this: 我定义了一个看起来像这样的地图:
map<int, string> testmap = {
{ 0, "a" },
{ 1, "b" },
{ 2, "c" }
}
However, I need to retrieve a value from testmap
using a uint64_t
value provided by another function. 但是,我需要使用另一个函数提供的uint64_t
值从testmap
检索一个值。
When I do testmap[my_uint64_t_value]
it returns an empty string, so I think this is because it's adding my_uint64_t_value
as a key and setting the value to NULL
. 当我执行testmap[my_uint64_t_value]
它返回一个空字符串,所以我认为这是因为它将my_uint64_t_value
添加为键并将其值设置为NULL
。
This is the same if I set the map type to <uint64_t, string>
, at least the way I'm currently defining my keys. 如果将映射类型设置为<uint64_t, string>
,至少在当前定义键的方式上,这是相同的。
However, is there a way that I either: 但是,有没有一种方法可以:
uint64_t
value to a regular int
将uint64_t
值转换为常规int
<uint64_t, string>
, and be able to define my keys as the 'correct' type? 将地图定义为<uint64_t, string>
,并能够将我的键定义为“正确”类型? It seems like int
type conversion isn't that common, is this something that should be avoided? 似乎int
类型转换并不常见,应该避免这种情况吗?
The reason why you get an empty string is std::map::operator[] returns a reference to the value if and only if it exists , otherwise it performs an insertion . 得到空字符串的原因是std :: map :: operator [] 当且仅当该值存在时才返回对该值的引用,否则它将执行插入 。 I suspect you have the latter case. 我怀疑你有后一种情况。
You need to use std::map::find for search. 您需要使用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"; }
Like @Rene mentioned in the comments, casting from uint64_t
to int
can cause overflow. 就像注释中提到的@Rene一样,从uint64_t
为int
可能导致溢出。 Therefore, making the key to larger type(as per requirement) would be a good idea. 因此,将密钥设为更大的类型(按要求)将是一个好主意。
std::map<uint64_t, std::string> testmap;
As said in another answer, the []
operator of the map class will perform an insertion with a default-constructed value if the key is not present in the map. 如另一个答案中所述,如果键不存在于映射中,则映射类的[]
运算符将使用默认构造的值执行插入。
You can first use the count
method to determine if the key is present in the map before accessing it. 您可以先使用count
方法来确定键,然后再访问它。
if(testmap.count(keyToFind))
return testmap[keyToFind];
else
report_key_not_found();
An alternative solution is to use the at
method to access the value. 另一种解决方案是使用at
方法访问值。 It will throw an std::out_of_range
exception if the key is not present instead of inserting a new key. 如果该键不存在,则将引发std::out_of_range
异常,而不是插入新键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.