小编Joh*_*ohn的帖子

在无序映射中使用 string_view 作为键的安全方法

我的类型 Val 包含 std::string thekey。

struct Val
{
std::string thekey;
float somedata;
}
Run Code Online (Sandbox Code Playgroud)

我想将我的类型放入无序映射中,以 key 作为键。出于内存和避免转换的原因,我希望将 std::string_view 作为键类型。使用 unique_ptr 时是否可以创建指向 val.thekey 的密钥?

std::unique_ptr<Val> valptr = ...;
std::unordered_map<std::string_view,std::unique_ptr<Val>> themap;
themap[std::string_view(valptr->thekey)] = std::move(valptr); // is this ok and safe?
Run Code Online (Sandbox Code Playgroud)

c++ c++17

5
推荐指数
1
解决办法
4633
查看次数

标签 统计

c++ ×1

c++17 ×1