# `tie`

    template <class A, class B>
    tied<A,B> tie(A& a, B& b);

This is a utility function that makes it more convenient to work with a function which returns a std::pair<>. The effect of the `tie()` function is to allow the assignment of the two values of the pair to two separate variables. The idea for this comes from Jaakko Järvi's Binders [1].

### Where Defined

`boost/utility.hpp`

### Example

An example of using the `tie()` function with the `vertices()` function, which returns a pair of type `std::pair<vertex_iterator,vertex_iterator>`. The pair of iterators is assigned to the iterator variables `i` and `end`.

      graph_traits< adjacency_list<> >::vertex_iterator i, end;
      for(tie(i,end) = vertices(G); i != end; ++i)
        // ...

Here is another example that uses `tie()` for handling operations with `std::set`.

    #include <set>
    #include <algorithm>
    #include <iostream>
    #include <boost/utility.hpp>

    int
    main(int, char*[])
    {
      {
        typedef std::set<int> SetT;
        SetT::iterator i, end;
        bool inserted;

        int vals[5] = { 5, 2, 4, 9, 1 };
        SetT s(vals, vals + 5);

        // Using tie() with a return value of pair<iterator,bool>

        int new_vals[2] = { 3, 9 };

        for (int k = 0; k < 2; ++k) {
          boost::tie(i,inserted) = s.insert(new_vals[k]);
          if (!inserted)
            std::cout << *i << " was already in the set." << std::endl;
          else
            std::cout << *i << " successfully inserted." << std::endl;
        }
      }
      {
        int* i, *end;
        int vals[6] = { 5, 2, 4, 4, 9, 1 };
        std::sort(vals, vals + 6);

        // Using tie() with a return value of pair<iterator,iterator>

        boost::tie(i,end) = std::equal_range(vals, vals + 6, 4);
        std::cout << "There were " << std::distance(i,end)
                  << " occurrences of " << *i << "." << std::endl;
        // Footnote: of course one would normally just use std::count()
        // to get this information, but that would spoil the example :)
      }
      return 0;
    }

The output is:

      3 successfully inserted.
      9 was already in the set.
      There were 2 occurrences of 4.

Copyright © 2000 | Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu) Lie-Quan Lee, Univ.of Notre Dame (llee1@lsc.nd.edu) Andrew Lumsdaine, Univ.of Notre Dame (lums@lsc.nd.edu)