简体   繁体   中英

looping through a vector of iterators with an iterator

I get an error in the final for loop:

error: conversion from '__normal_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> >*,vector<__gnu_cxx::__normal_iterator<int*, std::vector<int> >>>' to non-scalar type '__normal_iterator<const int*,vector<int>>' requested

   20 | for(vector<int>::const_iterator t=ind.begin(); t != ind.end(); ++t){

      |                                   ~~~~~~~~~^~

I kept looking for solutions to similar problems and I still don't get what I did wrong.

#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,a;
vector<int>::iterator b;
cin>>n>>m;
vector<int> seq(n);
vector<vector<int>::iterator> ind;
for(int i=0;i<n;i++){
    cin>>seq[i];
}
for(int i=0;i<m;i++){
    cin>>a;
    b=find(seq.begin(),seq.end(),a);
    if(b!=seq.end()){
        ind.push_back(b);
    }
}
sort(ind.begin(),ind.end());
for(vector<int>::const_iterator t=ind.begin(); t != ind.end(); ++t){
    cout<<*t;
}
return 0;
}

vector<int>::const_iterator is an iterator for a vector of int . An iterator for a vector of iterators is vector<vector<int>::iterator>::const_iterator .

To avoid typing such monster types, use auto :

for(auto t=ind.begin(); t != ind.end(); ++t){
    cout<<*t;
}

or when you iterate from begin till end, a range based loop:

for(auto t : ind){
    cout<<t;
}

As you didnt include the error (at the time of writing this) I fixed only the obvious error. I suppose you need to dereference the iterator to print the actual element (ie add a * in both examples above).

The vector ind is a vector of elements of the type std::vector<int>::iterator .

So in the for loop you have to write at least like

vector<vector<int>::iterator>::const_iterator t=ind.begin();

And it seems within the loop you mean

 cout<<**t;

instead of

cout<<*t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM