C++ STL 算法另类使用方法2007-12-28 13:18:27 来源:中国自学编程网 作者: 点击:
很多时候我们希望在一个 vector ,或者 list ,或者什么其他东西里面,找到一个值在哪个位置,这个时候 find 帮不上忙,而有人就转而求助手写循环了,而且是原始的手写循环: ![]() 很多时候我们希望在一个 vector ,或者 list ,或者什么其他东西里面,找到一个值在哪个位置,这个时候 find 帮不上忙,而有人就转而求助手写循环了,而且是原始的手写循环:
for ( int i = 0; i < vect.size(); ++i) if ( vect[i] == value ) break; 如果编译器把 i 看作 for scope 的一部分,你还要把 i 的声明拿出去。真的需要这样么?看看这个: int dist = distance(col.begin(), find(col.begin(), col.end(), 5)); 其中 col 可以是很多容器,list, vector, deque... 当然这是你确定 5 就在 col 里面的情形,如果你不确定,那就加点判断: int dist; list<int>::iterator pos = find(col.begin(), col.end(), 5); if ( pos != col.end() ) dist = distance(col.begin(), pos); 我想这还是比手写循环来的好些吧。 -------------------------------------------------------------------------- max, min 这是有直接的算法支持的,当然复杂度是 O(n),用于未排序容器,如果是排序容器...老兄,那还需要什么算法么? max_element(col.begin(), col.end()); min_element(col.begin(), col.end()); 注意返回的是 iterator ,如果你关心的只是值,那么好: *max_element(col.begin(), col.end()); *min_element(col.begin(), col.end()); max_element 和 min_element 都默认用 less 来排序,它们也都接受一个 binary predicate ,如果你足够无聊,甚至可以把 max_element 当成 min_element 来用,或者反之: *max_element(col.begin(), col.end(), greater<int>()); // 返回最小值! *min_element(col.begin(), col.end(), greater<int>()); // 返回最大值 当然它们的本意不是这个,而是让你能在比较特殊的情况下使用它们,例如,你要比较的是每个元素的某个成员,或者成员函数的返回值。例如: #include <iostream> #include <list> #include <algorithm> #include <string> #include <boost/bind.hpp> using namespace boost; using namespace std; struct Person { Person(const string& _name, int _age) : name(_name), age(_age)
{} int age; string name; }; int main() { list<Person> col; list<Person>::iterator pos; col.push_back(Person("Tom", 10)); col.push_back(Person("Jerry", 12)); col.push_back(Person("Mickey", 9)); Person eldest = *max_element(col.begin(), col.end(), bind(&Person::age, _1) < bind(&Person::age, _2)); cout << eldest.name; } 输出是 Jerry ,这里用了 boost.bind ,原谅我不知道用 bind2nd, mem_fun 怎么写,我也不想知道... ------------------------------------------------------------------------- copy_if 没错,STL 里面压根没有 copy_if ,这就是为什么我们需要这个: template<typename InputIterator, typename OutputIterator, typename Predicate> OutputIterator copy_if( InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p) { while (begin != end) { if (p(*begin))*destBegin++ = *begin; ++begin; } return destBegin; } 把它放在自己的工具箱里,是一个明智的选择。 ------------------------------------------------------------------------ 惯用手法:erase(iter++) 如果你要去除一个 list 中的某些元素,那可千万小心:(下面的代码是错的!!!) #include <iostream> #include <algorithm> #include <iterator> #include <list> int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::list<int> lst(arr, arr + 10); for ( std::list<int>::iterator iter = lst.begin(); iter != lst.end(); ++iter) 相关文章: |