C++ primer上给出的是C++11的写法,使用了auto,假如没有auto该怎么写这个搜索函数?迭代器的类型无法确定,不太会写
这个是C++ primer上的
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end – beg) / 2;
while(mid != end && *mid != sought) {
if(sought < *mid)
end = mid;
else
beg = mid + 1;
mid = beg + (end – beg) / 2;
}
这个是C++ primer上的
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end – beg) / 2;
while(mid != end && *mid != sought) {
if(sought < *mid)
end = mid;
else
beg = mid + 1;
mid = beg + (end – beg) / 2;
}
解决方案
20
加一个中间层,让模板函数推导出来。
template<class T, class U > void func2( T beg , T end , U sought ) { T mid = beg + ( end - beg ) / 2; while( mid != end && *mid != sought ) { if( sought < *mid ) end = mid; else beg = mid + 1; mid = beg + ( end - beg ) / 2; } } template<class T, class U> void func( const T& v , U sought ) { func2( v.begin() , v.end() , sought ); }