Home > Software engineering >  Why does " error: no match for 'operator<<' " occur when searching for the
Why does " error: no match for 'operator<<' " occur when searching for the

Time:09-21

I am looking for the positions of an element using find(); method, but for some reason it conflicts whit the cout<< and I don't understand why.

#include <bits/stdc  .h>

using namespace std;

int main() {
    int n, busquedas, num,
    vas=0, pet=0;
    vector <int> arreglo;

    cin>>n;
    for(int i = 0; i < n; i  ){
        cin>> num;
        arreglo.push_back(num);
    }
    cin>>busquedas;
    for(int i = 0; i < busquedas; i  ){
        cin>>num;
        std::vector<int>::iterator it = std::find(arreglo.begin(), arreglo.end(), num);  
        cout<<it; //Here the error occurs
    }
    return 0; }

Also I have tried to change the iterator to the auto type and it shows the same error.

CodePudding user response:

This error means that the << operator is not supported for the iterator type with std::cout. Try doing this if you want to see the distance of the iterator from the beginning of the vector.

std::cout << std::distance(arreglo.begin(), it) << std::endl;

Or this if you want the value in the array the iterator points to (thanks @Slava for the idea of the segfault avoidance).

if (it != arreglo.end())
    std::cout << *it << std::endl;

CodePudding user response:

Hey you cannot print iterator << operator is not overloaded for that.

You can either print the value at it - vec.begin() it will print the index of your element in Vector

You also should check it != vec.end().

  • Related