-2
#include <iostream>
#include <utility>
#include <vector>

int main() {
    std::vector<std::pair<int,int>> v;
    v.push_back({10,20});

    // This works
    std::cout << v[0].first << " " << v[0].second << "\n";

    // But I'd like to just be able to do
    std::cout << v[0] << "\n";
}

How can we print a vector of pairs instead of printing separate values of the pairs like v[i].first and v[i].second? I want to print like cout << v[i]; but it shows an error.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Because `pair` could be expanded around types that can't be printed and because there will be no universal agreement on what `<<` should look like for a `pair`, `pair` does not have a `<<`. That said, you can write your own. `std::ostream & operator<< (std::ostream & out, std::pair val) { code for required formatting goes here }` – user4581301 Jul 06 '22 at 20:06
  • 3
    See [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Jul 06 '22 at 20:06
  • 3
    And you could go a step further and write `std::ostream & operator<< (std::ostream & out, std::vector> val)` – user4581301 Jul 06 '22 at 20:09
  • 2
    @user4581301 should be passing the `vector` by const reference instead: `std::ostream& operator<< (std::ostream& out, const std::vector>& val)` instead – Remy Lebeau Jul 06 '22 at 20:37
  • Whoop. Good catch. – user4581301 Jul 06 '22 at 20:46

1 Answers1

1

std::pair does not have a defined operator<<. Therefore, you have to define it yourself.

You can use this template to print any std::pair<T, Y> you want, as long as T and Y have defined operator<< as well:

#include <iostream>
#include <utility>

template<typename T, typename Y>
auto operator<<(std::ostream& stream, std::pair<T,Y> const& p) -> std::ostream& {
    stream << p.first << ' ' << p.second;
    return stream;
}

auto main() -> int {
    std::pair<int,int> p{1, 2};
    std::cout << p << '\n';
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JRazek
  • 191
  • 2
  • 11
  • `template auto operator<<(std::ostream& os, const std::vector>& pair) -> std::ostream& { for(const auto& el : pair) os << el.first << ' ' << el.second << '\n'; return os; }` – Eriss69 Oct 29 '22 at 19:44