Salman Elgamal
Salman Elgamal

Reputation: 3

How to cin to a back_inserter or any inserter in c++?

So I was thinking of simplifying this snippet

#include <bits/stdc++.h>

using namespace std;

int n;
vector<int> A;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin >> n;
    for (int i = 0; i < n; i++) {
        int tmp;
        cin >> tmp;
        A.push_back(tmp);
    }
}

And because I have read about inserters and back_inserters recently I thought of using them right away and this is what I came up with

#include <bits/stdc++.h>

using namespace std;

int n;
vector<int> A;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin >> n;
    for (int i = 0; i < n; i++) cin >> *back_inserter(A);
}

But for some reason the compiler spits a gigantic error message which I can't fit here so here is the first sentence only as I think it is the most relevant.

error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'std::back_insert_iterator<std::vector<int> >')

Thanks for your help!

NOTE: before anybody comments on the use of global variables and the using namespace line, this code was intended for use only in competitive programming.

Upvotes: 0

Views: 272

Answers (2)

KamilCuk
KamilCuk

Reputation: 141020

You could read into a temporary variable.

for (int k, i = 0; i < n; i++) cin >> k, back_inserter(A) = k;
# or nicer:
for (int i = 0; i < n; i++) {
     int k;
     cin >> k;
     back_inserter(A) = k;
}

You could provide the missing overload and read into temporary variable in it:

template<typename T>
std::istream& operator>>(std::istream& is, std::back_insert_iterator<std::vector<T>> obj) {
    T tmp;
    is >> tmp;
    obj = tmp;
    return is;
}

int main() {
    for (int i = 0; i < n; i++) cin >> back_inserter(A);
}

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180595

In this case where you are just reading space separated values from the input stream until it ends, you can use std::copy to get the values from the stream. That would look like

std::copy(std::istream_iterator<int>(cin),
          std::istream_iterator<int>(),
          std::back_inserter(vector_name));

Upvotes: 3

Related Questions