我这里有这个小 for 循环(重命名的变量和类型):
vector<Iterator> validIterators;
for (auto itr = someStartIterator; itr != someVector.end(); itr++)
{
if (itr->foo() && itr->bar())
validIterators.push_back(itr); // Notice that I'm not deferencing the iterator when adding it to the vector
}
...
for (const auto& itr : validIterators)
{
// Do stuff with the iterator explicitly (e.g. std::distance),
// and not the object that it points (at least not at first).
}
有什么方法可以使用STL <algorithm>
使某些东西“更清洁”的功能?我不能在那种情况下使用 Boost,也不能使用 C++20 ranges 或 range-v3。
提前谢谢你。
最佳答案
算法,就其本质而言,对值序列进行操作。它们通过称为“迭代器”的中间对象与这些值序列进行交互。但从实现的角度来看,这是一个实现细节。可以肯定的是,这是必要的,但它仍然不是算法的真正组成部分。
因此,算法通常不会将迭代器暴露给用户提供的仿函数。 std::for_each
向仿函数传递一个从迭代器中提取的值,而不是迭代器本身。 std::sort
的谓词比较值对,而不是迭代器对。 std::copy_if
根据提供值的谓词复制值。等等。即使是基于范围的 for
循环本身也不公开迭代器。
算法通过它们的迭代器而不是迭代器本身来操纵值。
最好的办法是手动执行循环并将“对迭代器执行操作”部分折叠到条件测试部分。
for (auto itr = someStartIterator; itr != someVector.end(); itr++)
{
if (itr->foo() && itr->bar())
{
// Do stuff with the `itr` explicitly (e.g. std::distance).
}
}
关于c++ - 如何用 STL 实现替换这个 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039830/