Search code examples
c++cininserter

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.


Solution

  • 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);
    }