Printing a `vector<pair<int, int>>`

Here is my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
    vector<pair<int, int>> v;
    v.push_back({ 1, 5 });
    v.push_back({ 2,3 });
    v.push_back({ 1,2 });
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
}

I'm getting an error C2679 binary "=": no operator found which takes a right-hand operand of type "std::pair<int, int>" (or there is no acceptable conversion). I have no idea what this means, or why copy doesn't print. Without copy, there is no error, but I want to print out vector v. Is there some other way to do htis?

Upvotes: 0

Views: 1047

Answers (4)

Eriss69
Eriss69

Reputation: 69

In my opinion this is the fastest way what I know

template<typename T, typename Y>
auto operator<<(std::ostream& os, const std::vector<std::pair<T,Y>>& pair) -> std::ostream&
{
    for(const auto& el : pair)
        os << el.first << ' ' << el.second << '\n';
    return os;
}

Upvotes: 0

jignatius
jignatius

Reputation: 6494

There's no standard way to cout a std::pair because there is no stream insertion (<<) operator overload for it. You could instead use std::for_each:

std::for_each(
    v.begin(),
    v.end(),
    [](const auto& p) { std::cout << p.first << "," << p.second << std::endl; });

Upvotes: 1

bhristov
bhristov

Reputation: 3197

After you sort you can use a for-each loop to iterate over the vector container and print the pairs:

for(const pair<int,int>& x: v)
{
  cout << x.first << " " << x.second << "\n";
}

Upvotes: 2

ProXicT
ProXicT

Reputation: 1933

In your code, you're trying to print std::pair<int, int> using a function printing one int, that's not going to work.

Since std::ostream doesn't have an overload taking std::pair by default, you have to provide an overload for the operator<< taking the type std::pair<int, int> yourself:

// This is necessary because ADL doesn't work here since
// the std::ostream_iterator will be looking for the overload
// in the std namespace.
struct IntPair : std::pair<int, int> {
    using std::pair<int, int>::pair;
};

std::ostream& operator<<(std::ostream& o, const IntPair& p) {
    o << p.first << " " << p.second;
    return o;
}

int main() {
    std::vector<IntPair> v;
    v.push_back({ 1, 5 });
    v.push_back({ 2, 3 });
    v.push_back({ 1, 2 });
    std::sort(v.begin(), v.end());
    std::copy(v.begin(), v.end(), std::ostream_iterator<IntPair>(std::cout, " "));
}

Upvotes: 2

Related Questions