user3786689
user3786689

Reputation: 37

Access elements of individual tuple from a list of tuples

#include <iostream>
#include <fstream>
#include <list>
#include <tuple>

using namespace std;

int main()
{
    list<tuple<char,double,double>> XYZ_Widget_Store;

    ifstream infile;
    infile.open("data.text");

    char x; // S, P, R
    double a,b; 

    for(;infile >> x >> a >> b;){
        XYZ_Widget_Store.push_back(make_tuple(x,a,b));
    }

    infile.close();

    for(list<int>::iterator it = XYZ_Widget_Store.begin(); it !=
      XYZ_Widget_Store.end(); ++it){
        cout << *it.get<0> << endl;
    }
    return 0;
}

Let's say that the first item on my list contains a tuple ('a',1,1) how do I get the first element 'a' from that tuple? usually it is just get<0>(mytuple) but being in a list makes it difficult to understand. I want to iterate through the list and get every first element from every element in the list. The element of the list is itself a tuple.

Upvotes: 1

Views: 2253

Answers (3)

Pradhan
Pradhan

Reputation: 16737

If it is an list<T>::iterator, then *it will give you the corresponding object of type T. So, you need to use get<0>(*it) to access the appropriate tuple element. You have another error in your for loop : Instead of

list<int>::iterator it = XYZ_Widget_Store.begin()

you need

list<tuple<char,double,double>>::iterator it = XYZ_Widget_Store.begin().

If you are using C++11, you can also do

auto it = XYZ_Widget_Store.begin()

Upvotes: 0

Dan R
Dan R

Reputation: 1494

If you're going to use C++11, you might as well use other nice features like auto and the for-each loop. Here is how you might re-write that last for loop:

for (auto& tup : XYZ_Widget_Store) {
    cout << get<0>(tup) << endl;
}

Upvotes: 3

unxnut
unxnut

Reputation: 8839

You need to use get<0>(*it) to get the first element because it is the pointer to tuple. So, your statement in the for loop should be:

cout << get<0>(*it) << endl;

Upvotes: 0

Related Questions