简体   繁体   中英

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?

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";
}

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, " "));
}

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; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM