gpt4 book ai didi

c++ :将 std::map 转换为 std::map

转载 作者:行者123 更新时间:2023-12-02 18:54:29 25 4
gpt4 key购买 nike

假设我有一个私有(private)std::map在我的类(class)里std::map<std::string, double> 。我怎样才能将其转换为std::map<std::string_view, double>返回给用户?我想要下面的原型(prototype)

const std::map<std::string_view, double>&
MyClass::GetInternalMap() const;

最佳答案

您不应返回新的 map通过常量引用。您将返回对临时 map 的悬空引用当 GetInternalMap() 时被摧毁退出。如果你想返回一个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()};
}

关于c++ :将 std::map<std::string, double> 转换为 std::map<std::string_view, double>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66341235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com