简体   繁体   中英

Move vector into unordered_map

I want to store the file's content as a value in the 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)


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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