Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of Tuples in C++

Tags:

c++

I have tried every thing which i could but this code is giving me errors. Both syntax are not working. I have commented operator[] but please provide a solution for that as well.

#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;
}

while printing tuple in for loop i am getting error.

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

and for operator[ ]

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> > >}')
like image 614
Shailendra Gupta Avatar asked Oct 22 '16 05:10

Shailendra Gupta


2 Answers

#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;
}
like image 84
Jana Avatar answered Sep 28 '22 07:09

Jana


Your i is an iterator, which is sort of like a pointer, so you need to dereference it, not pass it to operator [] or at():

get<0>(*i);
like image 28
John Zwinck Avatar answered Sep 28 '22 07:09

John Zwinck