打印一个vector <pair <int,int >>

时间:2019-12-08 13:34:26

标签: c++ vector

这是我的代码:

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

我遇到错误C2679 binary "=": no operator found which takes a right-hand operand of type "std::pair<int, int>" (or there is no acceptable conversion)。我不知道这是什么意思,也不知道为什么copy无法打印。没有copy,就没有错误,但是我想打印出vector v。还有其他方法可以做htis吗?

3 个答案:

答案 0 :(得分:2)

排序之后,可以使用for-each循环遍历向量容器并打印对:

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

答案 1 :(得分:1)

在您的代码中,您尝试使用打印一个std::pair<int, int>的功能来打印int,但这将无法正常工作。

由于std::ostream在默认情况下没有重载std::pair,因此您必须为operator<<自己提供std::pair<int, int>类型的重载:

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

答案 2 :(得分:1)

有一种标准的方法来引出std::pair,因为它没有流插入(<<)运算符重载。您可以改用std::for_each

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