A fancy way to read a sequence of input. i.e vector

Revision en1, by tickbird, 2024-04-11 22:21:50

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)

Tags cleancode, c++, template, idiomatic

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English tickbird 2024-04-11 22:21:50 1047 Initial revision (published)