3

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

6

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).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • thank you now it works can you explain further why ** ? is it a pointer on a pointer or something? I'm kinda new to c++ – Youssef Maghrebi Mar 11 '20 at 18:49
  • 1
    @YoussefMaghrebi t is an iterator that "points" to iterators. So the first dereferencing gives an iterator that you need to dereference the second time to get the pointed value. – Vlad from Moscow Mar 11 '20 at 18:50