本文介绍了基于范围的循环C ++ 11用于范围(L,R)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++ 11没有针对范围整数序列的基于范围的循环。
C++11 hasn't range-based-loop for ranged integral sequence.
for(auto e : {0..10} ) // wouldn't compile!!!
所以我决定模拟它。
template< class T , bool enable = std::is_integral<T>::value >
struct range_impl
{
struct iterator
{
constexpr T operator * ()const noexcept { return value; }
iterator& operator ++()noexcept { ++value; return *this; }
friend
constexpr bool operator != (const iterator & lhs, const iterator rhs ) noexcept
{
return lhs.value != rhs.value;
}
T value;
};
constexpr iterator begin()const noexcept { return { first }; }
constexpr iterator end ()const noexcept { return { last }; }
T first;
T last ;
};
template< class T >
range_impl<T> range(T first , T last) noexcept
{
return {first, last};
}
int main(){
// print numbers in [ 0..10 ), i.e. 0 1 2 3 4 5 6 7 8 9
for(auto e : range(0,10) ) std::cout << e << ' ';
std::cout << std::endl;
}
问:如何推广ForwardIterator的这个方法?
Q: How to generalize this method for ForwardIterators?
示例:
template< class ForwardIterator, class T >
bool find(ForwardIterator first, ForwardIterator last, T const& value)
{
for(auto e: range(first, last) ) if (e == v) return true;
return false;
}
推荐答案
strong>
Specialization
template< class Iterator>
struct range_impl<Iterator, false>
{
range_impl(Iterator first, Iterator last)
: first(first), last(last)
{}
constexpr Iterator begin()const noexcept { return { first }; }
constexpr Iterator end ()const noexcept { return { last }; }
Iterator first;
Iterator last ;
};
测试:
int main(){
for(auto e : range(0,10) ) std::cout << e << ' ';
std::cout << std::endl;
const char* a[] = { "Say", "hello", "to", "the", "world" };
for(auto e : range(a, a + 5) ) std::cout << e << ' ';
std::cout << std::endl;
}
这篇关于基于范围的循环C ++ 11用于范围(L,R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!