简体   繁体   English

将向量移动到 unordered_map

[英]Move vector into unordered_map

I want to store the file's content as a value in the unordered_map .我想将文件的内容作为值存储在unordered_map中。 And I want to avoid any copy after the file reading.而且我想在文件读取后避免任何副本。 Is my example correct?我的例子正确吗?

// key - path, value - pair of file's content and the last update time
std::unordered_map<std::string_view, std::pair<std::vector<char>, std::filesystem::file_time_type>> filesCache;
    
std::ifstream file(std::string{path}, std::ios::binary);
std::vector<char> fileContents;
fileContents.reserve(std::filesystem::file_size(path));
fileContents.assign(std::istreambuf_iterator<char>(file),
                    std::istreambuf_iterator<char>());
        
// I need to keep the file's content up to date
filesCache.insert_or_assign(path, std::make_pair(std::move(fileContents), std::filesystem::last_write_time(path)));

Shouldn't I insert the key first and work with placed value then?我不应该先插入密钥然后使用放置的值吗?

std::ifstream file(std::string{path}, std::ios::binary);
auto& [fileContents, lastUpdateTime] = scriptsCache_[path];
lastUpdateTime = std::filesystem::last_write_time(path);

fileContents.reserve(std::filesystem::file_size(path));
fileContents.assign(std::istreambuf_iterator<char>(file),
                    std::istreambuf_iterator<char>());

Or are both examples the same?还是两个例子都一样? How to check it?如何检查?

They are the same (in the sense that the std::vector is not copied, just moving around for the insert_or_assign case)它们是相同的(在std::vector没有被复制的意义上,只是在insert_or_assign情况下移动)


A difference is that when the read failed,不同的是,当读取失败时,

  • 1st case: you simply haven't insert the node.第一种情况:您根本没有插入节点。
  • 2nd case: you need to remember remove the entry from the map.第二种情况:您需要记住从 map 中删除该条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM