gpt4 book ai didi

c++ - 在移出边界之前停止 directory_iterator

转载 作者:行者123 更新时间:2023-11-28 05:24:44 25 4
gpt4 key购买 nike

我正在尝试遍历目录并读取其中的图像,同时允许跳过每第 n 个文件。

我的代码目前看起来像这样:

// Count number of files in directory and reserve memory (take skipped slices into account)
std::experimental::filesystem::directory_iterator it_begin{path};
int count = count_if(it_begin, std::experimental::filesystem::directory_iterator(), [](const std::experimental::filesystem::directory_entry & d) {return !is_directory(d.path());});
auto maxCount = count - (count % (1 + skipSlices));
m_imageStack.reserve(maxCount);

// Read image stack and check for validity
int n = 0;
for (std::experimental::filesystem::v1::directory_iterator it(path); it != std::experimental::filesystem::v1::directory_iterator(); std::advance(it, 1 + skipSlices))
{
std::string filename{std::experimental::filesystem::v1::path(*it).string()};
cv::Mat image = cv::imread(filename);
m_imageStack.push_back(image);

n = n + 1 + skipSlices;
if (n == maxCount) break;
}

如果 skipSlices = 1,我只想读取每 2 张图像,等等。为了不超出范围,我在 for 循环中添加了一个中断条件。我现在的解决方案非常糟糕,我想摆脱中断,而是在 for 循环中使用更正确的停止条件。但是,我找不到告诉迭代器在前进太多之前停止的方法。有什么解决办法吗?

最佳答案

只需编写一个有限制的 advance 版本即可。

namespace detail {
template<class It, class Dist>
void advance_with_limit_impl(It& it, It end, Dist n, std::random_access_iterator_tag) {
if(n > 0) it += std::min(end - it, n);
else it += std::max(end - it, n);
}

template<class It, class Dist>
void advance_with_limit_impl(It& it, It end, Dist n, std::bidirectional_iterator_tag) {
if(n > 0) { while(n != 0 && it != end) { --n; ++it; } }
else { while (n != 0 && it != end) { ++n; --it; } }
}

template<class It, class Dist>
void advance_with_limit_impl(It& it, It end, Dist n, std::input_iterator_tag) {
while(n != 0 && it != end) { --n; ++it; }
}
}

template<class It>
void advance_with_limit(It& it, It end,
typename std::iterator_traits<It>::difference_type n) {
detail::advance_with_limit_impl(it, end, n,
typename std::iterator_traits<It>::iterator_category());
}

然后只需使用 advance_with_limit(it, {}, 1 + skipSlices)

关于c++ - 在移出边界之前停止 directory_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40789388/

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