簡體   English   中英

檢查路徑是否包含另一個 C++

[英]Check if path contains another in C++

我正在尋找實現類似的東西

if (basePath.contains(subPath)) {
    // subPath is a subPath of the basePath
}

我知道我可以通過遍歷subPath的父母,在途中檢查basePath來實現這一點。

std方法嗎?


std::filesystem::path("/a/b/").contains("/a/b/c/d") == true

可以迭代std::filesystem::path 使用std::search()檢查basePath是否具有等於subPath的元素序列:

#include <algorithm>

if (std::search(basePath.begin(), basePath.end(), subPath.begin(), subpath.end()) != basePath.end()) {
   // subPath is a subPath of the basePath
}

根據您的要求(即您認為是子路徑的內容),您可以嘗試分析std::filesystem::relative()的結果,例如:

bool is_subpath(const std::filesystem::path &path,
                const std::filesystem::path &base)
{
    auto rel = std::filesystem::relative(path, base);
    return !rel.empty() && rel.native()[0] != '.';
}

請注意,如果無法確定路徑關系或路徑匹配,則此 function 返回false

您可以遍歷兩個路徑中的項目:

for (auto b = basePath.begin(), s = subPath.begin(); b != basePath.end(); ++b, ++s)
{
    if (s == subPath.end() || *s != *b)
    {
        return false;
    }
}
return true;

https://en.cppreference.com/w/cpp/algorithm/mismatch 一行就可以輕松解決:

bool is_subpath(const fs::path& path, const fs::path& base) {
    const auto mismatch_pair = std::mismatch(path.begin(), path.end(), base.begin(), base.end());
    return mismatch_pair.second == base.end();
}

通過以下測試(Catch2):

TEST_CASE("is_subpath", "[path]") {
    REQUIRE( is_subpath("a/b/c", "a/b") );
    REQUIRE_FALSE( is_subpath("a/b/c", "b") );
    REQUIRE_FALSE( is_subpath("a", "a/b/c") );
    REQUIRE_FALSE( is_subpath(test_root / "a", "a") );
    REQUIRE( is_subpath(test_root / "a", test_root / "a") );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM