C++ 如何编写以boost::Range作为参数的函数?
这是实现我自己的函数(例如,C++ 如何编写以boost::Range作为参数的函数?,c++,boost,C++,Boost,这是实现我自己的函数(例如,DoSomethingWithRange)的一种好方法,它接受a作为参数吗 #include <iostream> #include <vector> #include <boost/range.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/adaptors.hpp> using namespace std; templat
DoSomethingWithRange
)的一种好方法,它接受a作为参数吗
#include <iostream>
#include <vector>
#include <boost/range.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
using namespace std;
template <typename RangeType>
void DoSomethingWithRange(const RangeType &range)
{
typename RangeType::const_iterator beginIt = boost::begin(range);
typename RangeType::const_iterator endIt = boost::end(range);
for(typename RangeType::const_iterator it = beginIt; it != endIt; ++it)
{
cout << *it << endl;
}
}
bool IsPos(int i)
{
return i>0;
}
int main(int , char** )
{
vector<int> test;
test.push_back(1);
test.push_back(-1);
DoSomethingWithRange(test | boost::adaptors::filtered(IsPos));
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
模板
void DoSomethingWithRange(常数范围类型和范围)
{
typename RangeType::const_迭代器beginIt=boost::begin(范围);
typename RangeType::const_迭代器endIt=boost::end(范围);
for(typename RangeType::const_iterator it=beginIt;it!=endIt;++it)
{
cout这对普通数组不起作用,因为不会定义RangeType::const\u迭代器
。当传入Boost.Range也支持的std::pair
时,它也不起作用
相反,您应该使用boost::range\u iterator::type
。这将适用于boost支持的所有类型。range:普通的iterable对象、数组和迭代器对
例如:
template <typename RangeType>
void DoSomethingWithRange(const RangeType &range)
{
typedef typename boost::range_iterator<const RangeType>::type const_iterator;
const_iterator endIt = boost::end(range);
for(const_iterator it = boost::begin(range); it != endIt; ++it)
cout << *it << endl;
}
int main(int, char** )
{
vector<int> test;
test.push_back(1);
test.push_back(-1);
DoSomethingWithRange(test);
int test2[] = {12,34};
DoSomethingWithRange(test2);
std::pair<int*,int*> test3(test2, test2+1);
DoSomethingWithRange(test3);
}
模板
void DoSomethingWithRange(常数范围类型和范围)
{
typedef typename boost::range_迭代器::type const_迭代器;
常量迭代器endIt=boost::end(范围);
for(const_iterator it=boost::begin(range);it!=endIt;++it)
库特