名稱空間
變體
操作

std::filesystem::path::compare

來自 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()),則返回小於、等於或大於 0 的值。比較是逐元素進行的,如同在兩個路徑上從 begin()end() 進行迭代,並比較每個元素的 native() 的結果。
2) 等價於 compare(path(str))
3) 等價於 compare(path(s))

目錄

[編輯] 引數

p - - 要與之比較的路徑
str - - 表示要與之比較的路徑的字串或字串檢視
s - - 表示要與之比較的路徑的空終止字串

[編輯] 返回值

若該路徑按字典序小於給定路徑,則為小於 0 的值。

若該路徑按字典序等於給定路徑,則為等於 0 的值。

若該路徑按字典序大於給定路徑,則為大於 0 的值。

[編輯] 異常

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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
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)
按字典順序比較兩個路徑
(函式) [編輯]