从元组列表中访问单个元组的元素

时间:2014-07-07 03:02:54

标签: c++ list stl 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;
}

假设我list上的第一项包含tuple ('a',1,1)如何从该元组中获取第一个元素'a'?通常它只是get<0>(mytuple)但是在列表中会让人难以理解。我想迭代列表并从列表中的每个元素获取每个第一个元素。 list的元素本身就是tuple

3 个答案:

答案 0 :(得分:2)

如果您要使用C ++ 11,您可以使用其他不错的功能,如auto和for-each循环。以下是您可能重写最后for循环的方法:

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

答案 1 :(得分:0)

您需要使用get<0>(*it)来获取第一个元素,因为it是指向元组的指针。所以,你在for循环中的陈述应该是:

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

答案 2 :(得分:0)

如果itlist<T>::iterator,则*it将为您提供类型T的相应对象。因此,您需要使用get<0>(*it)来访问适当的元组元素。您的for循环中有另一个错误:而不是

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

你需要

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

如果您使用的是C ++ 11,您也可以

auto it = XYZ_Widget_Store.begin()
相关问题