C++ で標準入力から文字列を n 回読みこむ
某人が書いてるコードでよくそういう処理が出てくるので簡単に出来ないか書いてみた。
#include <iostream> #include <iterator> #include <algorithm> #include <vector> int main(){ int n; std::cin >> n; std::vector<std::string> v{n} std::copy_n(std::istream_iterator<std::string>{std::cin}, v.size(), v.begin()); for(auto&& n : v){ std::cout << n << std::endl; } return 0; } /* input: 3 homu mami mado output: homu mami mado */
std::istream_iterator
を使って標準入力から受け取り、std::copy_n
で対象のコンテナへコピーしています。
int n; std::cin >> n
を std::get<int>(std::cin)
みたいにかければもうちょいスッキリするんですけどねえ。