tickbird's blog

By tickbird, history, 7 weeks ago, In English

Add this line on top of your code

template <typename T> istream& operator>>(istream& is, vector<T> &a) {
    copy_n(istream_iterator<T>(is), a.size(), a.begin()); return is;
}

then you can do following

vector<int> a(n);
cin >> a // read n int
vector<long long> a(n);
cin >> a // read n long long
vector<string> a(n);
cin >> a // read n string

vector<vector<int>> a(n, vector<int>(m));
for (auto &r: a) cin >> r; // read n by m matrix

now you don't need to write this every time

for (int i = 0; i < n; i++) {
    cin >> a[i];
}

or use macro or weird template.

you specified type and size at declaration of vector, so let cin handle it.

clean & minimal code change use of STL & portable & easy to understand. thus idiomatic

(disclaimer: don't try to read anything other than primitive and std::string because it's simply undefined, std::pair<int, int> is probably most obvious one but you can if you want to)

  • Vote: I like it
  • +6
  • Vote: I do not like it