Boost logo

Boost Users :

Subject: Re: [Boost-users] [graph] [beginner] How to use the "tie(...) feature" with standard c++ containers?
From: Christoph (c_p_at_[hidden])
Date: 2011-10-10 09:04:49


Hi Cedric,

On Mon, 2011-10-10 at 11:29 +0200, Cedric Laczny wrote:
[...]
> Please note that you are using a _copy_ here and thus you also return the
> iterators of a _copy_ but not of the "original" container. Therefore, I assume
> that the iterators returned are not valid and might even lead to a
> segmentation fault (as they do on my machine, since this container-copy is
> only valid during the execution of elements() ).
> Perhaps you want to try "const T& container" in the argument list.

The bright shine of conclusion comes over me. I feel a little bit less
stupid for a moment... The felling is gone.

By using the "&"-reference type the operations in 'elements' are done on
'the original'. Now a 2-tuple of std::list <int>::iterator of 'the
original' list is returned by 'elements'.
 
For completeness here is the not so unhappy example in which i use 'T&'
in stead of 'const T&' in stead of 'T' as the argument of function
'elements':

// begin code
#include <iostream>
#include <list>
#include <boost/tuple/tuple.hpp>

template <typename T>
boost::tuple < typename T::iterator, typename T::iterator>
elements ( T& container)
{
        return boost::make_tuple(container.begin(), container.end());
}

int main ()
{
        std::list <int> list;
        list.push_back(1);
        list.push_back(2);
        list.push_back(3);
        list.push_back(4);
        std::list <int>::iterator beg, end;
        
        for (boost::tie(beg, end) = elements <std::list<int> >(list); beg !=
end; ++beg)
        {
                std::cout << *beg << std::endl;
        }
        return 0;
}
// end code

Output is:
1
2
3
4

Thank you all for clearing things up.
Christoph


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