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.

5
  • 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. Commented Nov 17, 2014 at 15:06
  • Check this out for the printing part (easily adapted): stackoverflow.com/questions/14070940/c-printing-out-map-values Commented Nov 17, 2014 at 15:06
  • ...and this member function will access a tuple by index: cplusplus.com/reference/map/map/operator[] . To access the first tuple, *(m.begin()). Commented Nov 17, 2014 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<int,int, char> or similar. Commented Nov 17, 2014 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. Commented Nov 17, 2014 at 15:37

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

5 Comments

better const TUPLE& t = element.second;
Thanks, that's helpful! But how can i print the tuple and access the three vectors individually?
@Jette Are you just looking for std::get<>()? (note: I don't like linking to cplusplus, but apparently cppreference does not have a std::get entry).
@bitmask Hm, doesn't come up in search results (and I plain overlooked it in the non-member section).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.