2016-10-22 178 views
4

我已經嘗試了所有可以使用的東西,但是這段代碼給了我錯誤。 這兩種語法都不起作用。我評論過operator [],但也請提供解決方案。C++中的元組向量元素

#include <bits/stdc++.h> 
using namespace std; 
int main() { 
    typedef vector< tuple<int, int, int> > my_tuple; 
    my_tuple tl; 
    tl.push_back(tuple<int, int, int>(21,20,19)); 
    for (my_tuple::const_iterator i = tl.begin(); i != tl.end(); ++i) { 
     //cout << get<0>(tl[i]); 
     //cout << get<0>(tl[i]); 
     //cout << get<0>(tl[i]); 
     cout << get<0>(tl.at(i)); 
     cout << get<1>(tl.at(i)); 
     cout << get<2>(tl.at(i)); 
    } 

    return 0; 
} 

在打印元組for循環時出現錯誤。

error: no matching function for call to 'std::vector<std::tuple<int, int, int> >::at(std::vector<std::tuple<int, int, int> >::const_iterator&)' 

,併爲運營商[]

error: no match for 'operator[]' (operand types are 'my_tuple {aka std::vector<std::tuple<int, int, int> >}' and 'std::vector<std::tuple<int, int, int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const std::tuple<int, int, int>*, std::vector<std::tuple<int, int, int> > >}') 
+2

不要'#include '。你應該包括''和''和''。這些「東西」是你不應該使用的內部細節。 –

+0

[如何使用迭代器瀏覽矢量? (C++)](http://stackoverflow.com/questions/2395275/how-to-navigate-through-a-vector-using-iterators-c) – krzaq

回答

3

i是一個迭代器,這是有點像一個指針,所以你需要取消對它的引用,而不是將它傳遞給operator []at()

get<0>(*i); 
4
#include <bits/stdc++.h> 
using namespace std; 
int main() { 
    typedef vector< tuple<int, int, int> > my_tuple; 
    my_tuple tl; 
    tl.push_back(tuple<int, int, int>(21,20,19)); 
    for (my_tuple::const_iterator i = tl.begin(); i != tl.end(); ++i) { 
     cout << get<0>(*i) << endl; 
     cout << get<1>(*i) << endl; 
     cout << get<2>(*i) << endl; 
    } 
    cout << get<0>(tl[0]) << endl; 
    cout << get<1>(tl[0]) << endl; 
    cout << get<2>(tl[0]) << endl; 

    return 0; 
}