[英]C++ - Check if One Array of Strings Contains All Elements of Another
[英]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.