0

I want to have a tuple of vectors, something like {1,2,3,4},{5,6},{7,8,9}. The reason I need this, is I know a priori how many vectors I need, but not how long they'll be. So I thought this might be the best way to do this. Also in the end I want to save them to a map, because I need several of these tuples later and so that I can access them by index.

For a start I thought about something like:

#include <vector>
#include <tuple>
#include <iostream>
#include <map>

using namespace std;

typedef vector<int> VECTOR;
typedef tuple<VECTOR, VECTOR, VECTOR> TUPLE;
typedef map<int, TUPLE> MAP;

int main()
{
    MAP m;
    VECTOR v1, v2, v3;
    TUPLE t;

    v1 = { 1, 2, 3, 4 };
    v2 = { 5, 6 };
    v3 = { 7, 8, 9 };

    t = make_tuple(v1, v2, v3);

    m.insert(pair<int, TUPLE>(1, t));

    return 0;
}

How can I print my map and how can I access the tuple in it?

EDIT: I know how to loop through a map, but not how to print a tuple of vectors.

Jette
  • 1
  • 3
  • 1
    Since they're all of the same type, why not an *array* of vectors instead? It will be easier to work with than a tuple. – Angew is no longer proud of SO Nov 17 '14 at 15:06
  • Check this out for the printing part (easily adapted): http://stackoverflow.com/questions/14070940/c-printing-out-map-values – Topological Sort Nov 17 '14 at 15:06
  • ...and this member function will access a tuple by index: http://www.cplusplus.com/reference/map/map/operator[]/ . To access the first tuple, *(m.begin()). – Topological Sort Nov 17 '14 at 15:08
  • Thanks so far. I already know how to loop through a map. The bigger problem is how to print a tuple of vectors. All I found for printing tuples was for tuples like tuple or similar. – Jette Nov 17 '14 at 15:29
  • @Jette Well, there is no *automatic* way to print a tuple of vectors, if that's what you're after (just as there is no automatic printing of a vector, or of a tuple). You'll have to print them yourself - perhaps accessing each element of the tuple in turn and printing the vector in whatever way you need. – Angew is no longer proud of SO Nov 17 '14 at 15:37

1 Answers1

2

If you are using C++11 you can do the following

for (auto element : m)  // iterate over map elements
{
    int key = element.first;
    TUPLE const& t = element.second;  // Here is your tuple

    VECTOR const& v1 = std::get<0>(t); // Here are your vectors
    VECTOR const& v2 = std::get<1>(t);
    VECTOR const& v3 = std::get<2>(t);
}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218