0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[競プロ]C++20でコンテナをcoutへの引数にする方法

Last updated at Posted at 2025-02-02

競技プログラミングで、以下のようにコンテナの中身を改行区切りでSTDINに出力したいとき用。

使用例
    std::vector<int> v{1, 2, 3};
    
    std::cout << v << '\n'; // 1\n 2\n 3\n\n

実装例

簡単には以下のようにすれば良い。

#include <iostream>
#include <ranges>
#include <concepts>
#include <string_view>

// range output
template<class T>
  requires std::ranges::input_range<T> && (!std::convertible_to<T, std::string_view>)
    std::ostream& operator << (std::ostream& cout, const T& v) {
  for (const auto& i : v) {
    cout << i << '\n';
  }
    
  return cout;
}

要素型がstd::ostreamへの出力に対応している必要がある点と、std::string系を別扱いにしないと文字列が1文字づつ分割されてしまう点に注意。

最後に

競プロ向けです。実開発でもデバッグ出力として使えるかもしれませんが、これを使うぐらいならstd::to_stringを使用するかログ機能を自作したほうがいいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?