检查路径是否包含 C++ 中的另一个

问题描述 投票:0回答:3

我希望实现类似的目标

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

c++ std
3个回答
2
投票

根据您的要求(即您认为是子路径),您可以尝试分析 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] != '.';
}

注意,如果无法确定路径关系,或者路径匹配,此函数将返回

false


1
投票

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") );
}

0
投票

您可以迭代两个路径中的项目:

for (auto b = basePath.begin(), s = subPath.begin(); b != basePath.end(); ++b, ++s)
{
    if (s == subPath.end() || *s != *b)
    {
        return false;
    }
}
return true;
© www.soinside.com 2019 - 2024. All rights reserved.