Namespaces
Variants

std::filesystem:: hash_value

From cppreference.net
定義済みヘッダー <filesystem>
std:: size_t hash_value ( const std:: filesystem :: path & p ) noexcept ;
(C++17以降)

目次

パラメータ

p - a std::filesystem::path object

戻り値

2つのパスについて、 p1 == p2 ならば hash_value ( p1 ) == hash_value ( p2 ) となるようなハッシュ値。

戻り値は std::hash と一致します。

注記

2つのパスの等価性は各コンポーネントを個別に比較することで判定されます。したがって、例えば "a//b" "a/b" と等しく、同じ hash_value を持ちます。

hash_value Boost.filesystem ライブラリに由来し、boost.hashとの相互運用性のために使用されていました(boost.hashは 実引数依存の名前探索 によって見つかった hash_value または利用可能な場合は boost::hash_value を呼び出します)。

#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)
              << fs::hash_value(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);
    // unordered_* コンテナで使用するハッシュ関数オブジェクト:
    struct PathHash
    {
        std::size_t operator()(fs::path const& p) const noexcept
        {
            return fs::hash_value(p);
        }
    };
    std::unordered_set<fs::path, PathHash> 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"

関連項目

2つのパスの字句表現を辞書順で比較する
(public member function)
(C++17) (C++17) (until C++20) (C++17) (until C++20) (C++17) (until C++20) (C++17) (until C++20) (C++17) (until C++20) (C++20)
2つのパスを辞書順で比較する
(function)
(C++17)
2つのパスが同じファイルシステムオブジェクトを参照しているかチェックする
(function)
(C++11)
ハッシュ関数オブジェクト
(class template)
std::filesystem::path のハッシュサポート
(class template specialization)