名稱空間
變體
操作

std::hash<std::filesystem::path>

來自 cppreference.com
< cpp‎ | filesystem‎ | path
 
 
 
 
定義於標頭檔案 <filesystem>
template<>
struct hash<std::filesystem::path>;
(C++17 起)

std::hashstd::filesystem::path 的模板特化允許使用者獲取 std::filesystem::path 的雜湊值。

此特化的 operator()noexcept。對於每個 std::filesystem::pathpstd::hash<std::filesystem::path>{}(p) 等同於 std::filesystem::hash_value(p)

此特化在 C++17 標準釋出時缺失,參見 LWG issue 3657

[編輯] 示例

#include <cassert>
#include <cstddef>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <unordered_set>
namespace fs = std::filesystem;
 
void show_hash(fs::path const& p)
{
    std::cout << std::hex << std::uppercase << std::setw(16)
              << std::hash<fs::path>{}(p) << " : " << p << '\n';
}
 
int main()
{
    auto tmp1 = fs::path{"/tmp"};
    auto tmp2 = fs::path{"/tmp/../tmp"};
    assert(!(tmp1 == tmp2));
    assert(fs::equivalent(tmp1, tmp2));
    show_hash(tmp1);
    show_hash(tmp2);
 
    for (auto s : {"/a///b", "/a//b", "/a/c", "...", "..", ".", ""})
        show_hash(s);
 
    std::unordered_set<fs::path, std::hash<fs::path>> dirs{
        "/bin", "/bin", "/lib", "/lib", "/opt", "/opt", "/tmp", "/tmp/../tmp"};
    for (fs::path const& p : dirs)
        std::cout << p << ' ';
    std::cout << '\n';
}

可能的輸出

6050C47ADB62DFE5 : "/tmp"
62795A58B69AD90A : "/tmp/../tmp"
FF302110C9991974 : "/a///b"
FF302110C9991974 : "/a//b"
FD6167277915D464 : "/a/c"
C42040F82CD8B542 : "..."
D2D30154E0B78BBC : ".."
D18C722215ED0530 : "."
               0 : ""
"/tmp/../tmp" "/opt" "/lib" "/tmp" "/bin"

[編輯] 參閱

(C++11)
雜湊函式物件
(類模板) [編輯]
計算路徑物件的雜湊值
(函式) [編輯]