std::filesystem::path::compare
From cppreference.com
< cpp | filesystem | path
| int compare( const path& p ) const noexcept; |
(1) | (C++17以降) |
| int compare( const string_type& str ) const; int compare( std::basic_string_view<value_type> str ) const; |
(2) | (C++17以降) |
| int compare( const value_type* s ) const; |
(3) | (C++17以降) |
パスの字句表現と別のパスを比較します。
1) root_name().native().compare(p.root_name().native()) がゼロでない場合、その値を返します。
それ以外の場合、has_root_directory() != p.has_root_directory() であれば、
has_root_directory() が false の場合はゼロ未満の値を、それ以外の場合はゼロより大きい値を返します。 それ以外の場合、パスの相対部分(
relative_path())が、p の相対部分(p.relative_path())と比較して、それぞれ字句的に小さい、等しい、または大きい場合に、ゼロ未満、ゼロ、またはゼロより大きい値を返します。比較は要素ごとに行われ、あたかも両方のパスを begin() から end() まで反復処理し、各要素の native() の結果を比較するかのように行われます。2) compare(path(str)) と同等です。
3) compare(path(s)) と同等です。
目次 |
[編集] パラメータ
| p | - | 比較対象のパス |
| str | - | 比較対象のパスを表す文字列または文字列ビュー |
| s | - | 比較対象のパスを表すヌル終端文字列 |
[編集] 戻り値
パスが与えられたパスより字句的に小さい場合、ゼロ未満の値を返します。
パスが与えられたパスと字句的に等しい場合、ゼロを返します。
パスが与えられたパスより字句的に大きい場合、ゼロより大きい値を返します。
[編集] 例外
2,3) 実装定義の例外をスローする場合があります。
[編集] 注意
双方向比較の場合、二項演算子の方が適している場合があります。
[編集] 例
このコードを実行
#include <filesystem> #include <iostream> #include <string_view> namespace fs = std::filesystem; void demo(fs::path p1, fs::path p2, std::string_view msg) { std::cout << p1; const int rc = p1.compare(p2); if (rc < 0) std::cout << " < "; else if (rc > 0) std::cout << " > "; else std::cout << " == "; std::cout << p2 << " \t: " << msg << '\n'; } int main() { demo("/a/b/", "/a/b/", "simple"); demo("/a/b/", "/a/b/c", "simple"); demo("/a/b/../b", "/a/b", "no canonical conversion"); demo("/a/b", "/a/b/.", "no canonical conversion"); demo("/a/b/", "a/c", "absolute paths order after relative ones"); }
出力
"/a/b/" == "/a/b/" : simple "/a/b/" < "/a/b/c" : simple "/a/b/../b" > "/a/b" : no canonical conversion "/a/b" < "/a/b/." : no canonical conversion "/a/b/" > "a/c" : absolute paths order after relative ones
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2936 | C++17 | すべてのパス要素を直接比較 | ルート名とルートディレクトリは個別に処理 |
[編集] 関連項目
| (C++17)(C++17)(C++20まで)(C++17)(C++20まで)(C++17)(C++20まで)(C++17)(C++20まで)(C++17)(C++20まで)(C++20) |
2つのパスを辞書順に比較します (function) |