C++:将 std::map<std::string, double> 转换为 std::map<std::string_view, double>

Dmi*_*try 2 c++ c++17

假设std::map我的班级中有一个 private std::map<std::string, double>。我怎样才能转化为std::map<std::string_view, double>返回给用户?我想在这里有以下原型

const std::map<std::string_view, double>&
MyClass::GetInternalMap() const;
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

你不应该map通过 const 引用返回新的。您将返回对退出map时被破坏的临时值的悬空引用GetInternalMap()。如果要返回 const 引用,则应按map原样返回源,例如:

const std::map<std::string, double>& MyClass::GetInternalMap() const
{
    return myvalues;
}
Run Code Online (Sandbox Code Playgroud)

否则,map改为按值返回新的:

std::map<std::string_view, double> MyClass::GetInternalMap() const;
Run Code Online (Sandbox Code Playgroud)

话虽如此, astd::map<std::string,double>不能直接转换为 a std::map<std::string_view,double>,因此您必须一次手动迭代源map一个元素,将每个元素分配给 target 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;
}
Run Code Online (Sandbox Code Playgroud)

幸运的是, astd::pair<std::string,double>可以隐式转换为 a std::pair<std::string_view,double>,因此您可以简单地使用将map迭代器范围作为输入的构造函数,然后map为您分配元素,例如:

std::map<std::string_view, double> MyClass::GetInternalMap() const
{
    return {myvalues.begin(), myvalues.end()};
}
Run Code Online (Sandbox Code Playgroud)