Tuple vector in C ++

I tried everything I could, but this code gives me errors. Both syntaxes do not work. I commented on the operator [], but please provide a solution for this.

#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 a tuple in a loop, I get an 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 the 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> > >}')
+6
source share
3 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;
}
+8
source

Yours iis an iterator that seems to be a pointer, so you need to dereference it, not pass it to operator []or at():

get<0>(*i);
+4
source
#include <bits/stdc++.h>
using namespace std;
int main() {
    vector<tuple<int,string,int>> vt;
    vt.push_back({421,"cha",10});
    vt.push_back({464,"sam",20});
    vt.push_back({294,"sac",30});
    for(const auto &i : vt)
        cout<<get<0>(i)<<"  "<<get<1>(i)<<"  "<<get<2>(i)<<endl;
return 0;
}
0
source

Source: https://habr.com/ru/post/1658520/


All Articles