[Home]STLAlgorithmExtensions/IndexAlgorithms

BOOST WIKI | STLAlgorithmExtensions | RecentChanges | Preferences | Page List | Links List

Difference (from revision 1 to current revision) (minor diff)
(The revisions are identical or unavailable.)
All of the algorithms below find some indices in a container. As I remember, they all were usefull some time ago, but don't ask me why iterators won't do. I don't remember. Probably, because iterators are not stable, or for some other reason.

    template<class Container, class T>
        inline typename Container::difference_type
        find_index(const Container &container, const T& value)
        {
            const typename Container::const_iterator i = find(container, value);
            if (i != container.end()) return distance(container.begin(), i);
            return -1;
        }

    template<class Container, class Predicate>
        inline typename Container::difference_type
        find_index_if(const Container &container, Predicate pred)
        {
            const typename Container::const_iterator i = find_if(container, pred);
            if (i != container.end()) return distance(container.begin(), i);
            return -1;
        }

    template<class InputIterator, class Predicate>
        std::vector<int>
        find_all_indices_if(InputIterator b, InputIterator e, Predicate pred)
        {
            std::vector<int> result;
            for (InputIterator i = b; i != e; i++)
                if (pred(*i)) result.push_back(distance(b, i));
            return result;
        }

    template<class Container, class Predicate>
        inline std::vector<int>
        find_all_indices_if(Container &container, Predicate pred)
        {
            return find_all_indices_if(container.begin(), container.end(), pred);
        }

    template<class InputIterator, class T>
        inline std::vector<int>
        find_all_indices(InputIterator b, InputIterator e, const T &t)
        {
            return find_all_indices_if(b,e, bind2nd(std::equal_to<T> (), t));
        }

    template<class Container, class T>
        inline std::vector<int>
        find_all_indices(Container &container, const T& t)
        {
            return find_all_indices(container.begin(), container.end(), t);
        }
 

-- People/Vladimir Prus

One use case: if we use vector to implement int->something mapping (as often happens with BGL), then to do reverse lookup one can use

   find_index(components, something(...))
which is a lot more concise than
   distance(find(components, something(...)), components.begin());


BOOST WIKI | STLAlgorithmExtensions | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited September 27, 2004 9:05 am (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers