我正在尝试将所选元素从一个路径追加到另一个路径。但是path.append方法并不像我期望的那样工作。看看它的实现,它将接受来自字符串的元素,但不接受来自路径的元素,这看起来很奇怪。给定一对选择一系列路径元素的路径迭代器,我认为无法将其附加到现有路径或使用它来初始化新路径。
#include <filesystem>
using namespace std;
void TestPathAppend()
{
path path1("c:\\dir1\\dir2");
// Fails - constructor cannot construct a path from selected path elements.
path path2(path1.begin(), path1.end());
// Ok - constructor _can_ construct a path from a random chunk of string.
string random("stuff");
path path3(random.begin(), random.end());
// Fails - path.append cannot append path elements.
path path4;
path4.append(path1.begin(), path1.end());
// Ok. path.append can append elements from a random chunk of string.
string random("someoldcobblers");
path4.append(random.begin(), random.end());
// What I want to do but can't.
path::iterator temp = path1.begin();
advance(temp, 2);
path4.append(temp, path1.end());
}
更一般地说,路径类接口看起来设计得很糟糕。它公开了begin()和end()方法,可以迭代路径的元素,给人的印象是它将路径抽象为一组可迭代的路径元素,但没有push,pop,append或constructor。实际上可以使用您可以迭代的路径元素的方法。它有一个接受迭代器范围对的构造函数和append()方法,但是它甚至不能接受其他路径迭代器,只能用于字符串迭代器,这完全是多余的,因为你已经可以从字符串构造一个路径并附加一个路径到另一个,所以这些字符串迭代器方法甚至不启用任何其他功能,它们只是复制已经可用的功能。
我是否误解了这种类型的用途?
实现我想要做的最好方法是什么?
答案 0 :(得分:0)
这是你想做的事吗?
#include <iostream>
#include <filesystem>
#include <numeric>
int main()
{
path ab("/a/b");
path cdefgh("c/d/e/f/g/h");
auto first = std::next(cdefgh.begin(), 2);
auto last = std::next(cdefgh.begin(), 5);
auto adefh = std::accumulate(first, last, ab,
[](auto p, const auto& part)
{
return p /= part;
});
std::cout << adefh << std::endl;
}
预期结果:
"/a/b/e/f/g"
答案 1 :(得分:0)
我发现同样的问题要求Boost实施,解决方案适用于VS2012。
void TestPathAppend()
{
path path1("c:\\dir1\\dir2");
path::iterator temp = path1.begin();
advance(temp, 2);
path path2;
while(temp != path1.end())
{
path2 /= *temp;
++temp;
}
}
虽然看起来确实不必要地笨拙,但并不真正符合标准库其余部分的设计理念。例如。如果path暴露了标准的可迭代集合接口,我可以使用copy方法或back_inserter迭代器来完成此操作,而不需要手动循环。