2014-07-07 131 views
1
#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访问元素

+0

有什么理由你第一个'for'循环没有写成'while'? –

回答

2

如果你要使用C++ 11,你还不如用其他不错的功能auto和for-each循环。下面是你可能会重新写,去年for循环:

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

谢谢,我其实并不熟悉这个功能 – user3786689

0

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

cout << get<0>(*it) << endl; 
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()