00001 #ifndef STL_UTILS 00002 #define STL_UTILS 00003 00004 #include <utility> 00005 #include <vector> 00006 #include <iostream> 00007 00008 // ==================================================================================== 00009 // stl_utils.h 00010 // This file contains some utility functions for dealing with the STL. 00011 // ==================================================================================== 00012 00013 00014 /// Functor to get the first element of a pair. Use with STL functions like transform(). 00015 struct get_first { 00016 template <typename P> 00017 typename P::first_type operator()(const P& pair) { 00018 return pair.first; 00019 } 00020 }; 00021 00022 /// Functor to get the second element of a pair. Use with STL functions like transform(). 00023 struct get_second { 00024 template <typename P> 00025 typename P::second_type operator()(const P& pair) { 00026 return pair.second; 00027 } 00028 }; 00029 00030 00031 template <typename Indexable> 00032 struct indexed_lt_functor { 00033 const Indexable& container; 00034 indexed_lt_functor(const Indexable& c) : container(c) { } 00035 template <typename I> 00036 bool operator()(const I& lhs, const I& rhs) { 00037 return container[lhs] < container[rhs]; 00038 } 00039 }; 00040 00041 template <typename Indexable> 00042 indexed_lt_functor<Indexable> indexed_lt(const Indexable& container) { 00043 return indexed_lt_functor<Indexable>(container); 00044 } 00045 00046 00047 template <typename Index> 00048 void invert(std::vector<Index>& vec) { 00049 std::vector<Index> inverse(vec.size()); 00050 for (size_t i=0; i < vec.size(); i++) { 00051 inverse[vec[i]] = i; 00052 } 00053 inverse.swap(vec); 00054 } 00055 00056 00057 /// 00058 /// Generator object for a strided sequence of ints. 00059 /// 00060 struct sequence { 00061 int value, stride; 00062 00063 sequence(int _start=0, int _stride=1) 00064 : value(_start), stride(_stride) { } 00065 00066 int operator()() { 00067 int result = value; 00068 value += stride; 00069 return result; 00070 } 00071 }; 00072 00073 00074 00075 00076 #endif // STL_UTILS