在嵌套地图中搜索C++
我有一个嵌套地图:
std::map<std::string,std::map<std::string,float>> registration_by_date_time;
其中键是日期的字符串,而值是另一个映射,其中包含键a字符串的时间端值a float。
我必须实现此方法:
float get_registration(const string & date, const string & time) const;
哪个在日期和时间返回时间序列值,或者如果以前未添加该值 时间序列。
我的实施是:
float get_registration(const string & date, const string & time) const{
if(registration_by_date_time.find(date) != registration_by_date_time.cend())
if(registration_by_date_time.at(date).find(time) != registration_by_date_time.at(date).cend())
return registration_by_date_time[date][time];
else
return "NaN";
else
return "NaN";
}
正确吗?特别是我想知道我是否正确使用。
I have a nested map:
std::map<std::string,std::map<std::string,float>> registration_by_date_time;
where the key is a string for the date and the value is another map with key a string for time end value a float.
I have to implement this method:
float get_registration(const string & date, const string & time) const;
which returns the time series value at date and time or "NaN" in case the value was not previously added in
the time series.
My implementation is the following:
float get_registration(const string & date, const string & time) const{
if(registration_by_date_time.find(date) != registration_by_date_time.cend())
if(registration_by_date_time.at(date).find(time) != registration_by_date_time.at(date).cend())
return registration_by_date_time[date][time];
else
return "NaN";
else
return "NaN";
}
Is it correct? in particular I wold like to know if I am using correctly .at and if I also could use the access operator [] or "second".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,地图的索引运算符不是恒定操作(对于
std :: Map
访问为O(log(n)))。因此,在这里,您需要两次支付此费用 - 查找和第二次返回值(如果有)。一种更好的方法是存储发现的结果:正如指出的那样,此代码不仅较短,而且应该更快,避免使用CODED> o(log> o(log(n))的双重访问,这两个外部和内图。通常,我建议您可以在此处使用自动来使代码缩短,我已经明确地写出了该类型,希望使逻辑更清晰。
注意:STD :: MAP未使用hashmap实现,它是用红黑树(一种二进制搜索树)实现的,因此这可能使您认为访问的复杂性具有预期的恒定恒定复杂性。
Note that the index operator for map is not a constant operation (for
std::map
access is O(log(n))). So here you pay this cost twice - once for the find and second time to return the value (if available). A better approach is to store the result of find:As pointed out, not only is this code shorter but it should be faster, avoiding double access with cost
O(log(n))
for both the outer and the inner map. In general as I suggest you can use auto here to make the code shorter, I have written out the type explicitly in hope to make the logic clearer.NOTE: std::map is not implemented with a hashmap, it is implemented with red-black trees (a type of binary search tree), so it is possible this is what led you to think the complexity of access is with expected constant complexity.