[英]c++ : convert std::map<std::string, double> to std::map<std::string_view, double>
假设我的 class std::map<std::string, double>
中有一个私有的std::map
。 如何转换为std::map<std::string_view, double>
以返回给用户? 我想在这里有以下原型
const std::map<std::string_view, double>&
MyClass::GetInternalMap() const;
您不应通过 const 引用返回新的map
。 您将返回对在GetInternalMap()
退出时被破坏的临时map
的悬空引用。 如果要返回 const 引用,则应按原样返回源map
,例如:
const std::map<std::string, double>& MyClass::GetInternalMap() const
{
return myvalues;
}
否则,按值返回新的map
:
std::map<std::string_view, double> MyClass::GetInternalMap() const;
话虽如此, std::map<std::string,double>
不能直接转换为std::map<std::string_view,double>
,因此您必须手动迭代源map
一个元素时间,将每个分配给目标map
,例如:
std::map<std::string_view, double> MyClass::GetInternalMap() const
{
std::map<std::string_view, double> result;
for(auto &p : myvalues) {
result[p.first] = p.second;
// or: result.emplace(p.first, p.second);
}
return result;
}
幸运的是, std::pair<std::string,double>
可以隐式转换为std::pair<std::string_view,double>
,因此您可以简单地使用将迭代器范围作为输入的map
构造函数,并且让map
为您分配元素,例如:
std::map<std::string_view, double> MyClass::GetInternalMap() const
{
return {myvalues.begin(), myvalues.end()};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.