Boost logo

Boost Users :

Subject: Re: [Boost-users] [graph] [beginner] How to use the "tie(...) feature" with standard c++ containers?
From: Jeremiah Willcock (jewillco_at_[hidden])
Date: 2011-10-09 18:09:08


On Sun, 9 Oct 2011, Christoph wrote:

> Hi
>
> recently i started programming with the boost graph library. You can use
> nice syntax for iterating over a set of vertices or edges by writing for
> example:
>
> //begin program
> #include <iostream>
> #include <boost/graph/adjacency_list.hpp>
>
> typedef boost::adjacency_list < boost::listS, boost::vecS,
> boost::bidirectionalS>
> my_graph;
>
> typedef boost::graph_traits <my_graph>
> my_graph_traits;
>
> int main()
> {
> my_graph g(5);
> my_graph_traits::vertex_iterator vi, vi_end;
>
> for (boost::tie (vi, vi_end) = vertices (g); vi != vi_end; ++vi)
> {
> std::cout << "vertex: " << *vi << std::endl;
> }
> }
> //End program
>
> Outputs:
> vertex: 0
> vertex: 1
> vertex: 2
> vertex: 3
> vertex: 4
>
> My question is now how to define functions 'tie(...)' and
> 'elements(...)' for using them with standard containers.
>
> Suppose you have a container like the list:
>
> std::list <unsigned int> list(4);
>
> Now to iterate over all elements i would like to write something like
>
> //begin snippet
> std::list <unsigned int>::iterator begin, end;
> for (tie (begin, end) = elements (list); begin != end; ++begin)
> ;// do some thing
> //end snippet
>
> In stead of writing:
>
> //begin snippet
> begin = list.begin();
> end = list.end();
>
> for (; begin != end; ++begin)
> ;// do some thing
> //end snippet
>
> I started defining the function elements(...) like this:
>
> template <typename T>
> std::pair < typename T::iterator, typename T::iterator>
> elements (T container)
> {
> return std::make_pair(container.begin(), container.end());
> }
>
> The compiler tells me, that 'tie' was not declared in this scope. So i
> assume that i also have to define the 'tie' function in some way. Maybe
> there is already some functionality to access the standard containers
> the way you can do it with 'tie' or maybe you could give me some hint to
> solve the problem.

You need to use boost::tie if your iterator types are not already in the
boost namespace. The definition of tie is in Boost.Tuple, I think.

-- Jeremiah Willcock


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net