gpt4 book ai didi

c++ - 获取两个目录之间的路径 "difference"

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:17 26 4
gpt4 key购买 nike

情况:

我有一个或多个绝对路径,例如:

  1. /home/本杰明/测试/
  2. /home/benjamin/test/a/1
  3. /home/benjamin/test/b/1

如何区分两条路径?假设我想知道如何从路径 1 到达路径 2。预期结果将是

/home/benjamin/test/a/1 -/home/benjamin/test/=/a/1

有没有比将字符串彼此相减更优雅的方法?

最佳答案

我会尝试使用 std::mismatch ( documentation )

template <class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2 );

Return first position where two ranges differ

按顺序将 [first1,last1) 范围内的元素与从 first2 开始的范围内的元素进行比较,并返回第一个不匹配发生的位置。

部分代码:

string
mismatch_string( string const & a, string const & b ) {

string::const_iterator longBegin, longEnd, shortBegin;

if( a.length() >= b.length() ) {
longBegin = a.begin();
longEnd = a.end();
shortBegin = b.begin();
}
else {
longBegin = b.begin();
longEnd = b.end();
shortBegin = a.begin();
}

pair< string::const_iterator, string::const_iterator > mismatch_pair =
mismatch( longBegin, longEnd, shortBegin );

return string( mismatch_pair.first, longEnd );
}

A full example with outpu t 在键盘上传。

关于c++ - 获取两个目录之间的路径 "difference",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com