[英]std::for_each equivalent that does not dereference the iterators
是否有像std :: for_each這樣的函數直接傳遞迭代器而不是取消引用它們的結果?
我們有什么
std::vector<int> ints;
std::for_each(ints.begin(), ints.end(),
[](int i)
{
//how to get the iterator of this element???
}
我正在尋找什么
for_each_iterator(ints.begin(), ints.end(),
[](const std::vector<int>::const_iterator &i)
{
//we know the iterator here
}
當然,編寫這樣的函數是相當簡單的,但我問是否存在來自std::
, std::tr1::
或boost::
的標准解決方案
你正在尋找錯誤的抽象層次。 for_each
算法將函數應用於范圍中的每個元素 。 如果需要對迭代器進行操作,則應該展開循環:
for (auto it = ints.begin(); it != ints.end(); ++it ) {
// do something
}
你要求的東西可以輕易實現,在我看來並不是那么有用。 要么控制循環中迭代器的更新方式(如上面的代碼所示),要么迭代器本身幾乎沒用。 你想從迭代器中得到什么?
標准庫中沒有這樣的東西。 但是自己實現它並不困難:
template<typename It, typename Functor >
void iterate(It begin, It end, Functor && f)
{
while ( begin != end ) { f(begin); ++begin; }
}
並將其用作:
iterate(ints.begin(), ints.end(), [](std::vector<int>::iterator it)
{
//use it
});
或者使用手動循環。
我只能想到如何使用包裝器進行迭代器,我想不出只使用標准算法的方法,所以你仍然需要編寫一些輔助代碼。 例:
#include <algorithm>
#include <vector>
#include <iostream>
template<typename T>
struct it_wrapper {
it_wrapper(const T& t) : it(t) { }
T operator*() const {
return it;
}
it_wrapper& operator++() {
++it;
return *this;
}
it_wrapper operator++(int) {
it_wrapper old = *this;
++it;
return old;
}
bool operator!=(const it_wrapper& rhs) {
return it != rhs.it;
}
T it;
};
template<typename T>
it_wrapper<T> wrap(const T& t) {
return it_wrapper<T>(t);
}
int main() {
std::vector<int> v { 1, 2, 3, 4 };
std::for_each(wrap(v.begin()), wrap(v.end()), [](decltype(v.begin()) i) {
std::cout << *i << '\n';
});
}
打印
1
2
3
4
我不確定這比僅僅使用for
-loop更有幫助,但你必須有你的理由......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.