C ++使用copy显示对的向量

问题描述 投票:0回答:1
std::vector<std::pair<Pos, int>> v;
// sort and other stuff...
std::ostream_iterator<std::vector<std::pair<Pos, int>>> out_it(std::cout, "\n");
std::copy(v.begin(), v.end(), out_it); // error

目前正在研究STL并尝试使用copy打印到控制台。我有一个operator<<用于显示对,我应该制作一个用于显示向量?或者还有另一种方式吗? Pos只是我定义的一个类,它有一个私有成员字符串。

c++ vector printing copy std-pair
1个回答
1
投票

这将有效:

#include  <iostream>
#include  <vector>
#include  <iterator>

namespace std {
template <class T1, class T2>
    std::ostream& operator<<(std::ostream& out, const std::pair< T1, T2>& rhs)
    {
      out << "first: " << rhs.first << " second: " << rhs.second;
      return out;
    }
}

int main(){
    std::pair< size_t, int > pp(1,2);
    std::vector<std::pair< size_t, int >> v;
    v.push_back(pp);
    v.push_back(pp);
    v.push_back(pp);

    std::ostream_iterator<std::pair< size_t, int >> out_it(std::cout, "\n");
    std::copy(v.begin(), v.end(), out_it); 
}

std :: copy()从第一个参数给出的值迭代到第二个,使用第三个参数作为目标的迭代器。显然,类型应该匹配。

如果为向量流定义迭代器,则不需要std :: copy来输出单向量(应该是operator <<的代码)

© www.soinside.com 2019 - 2024. All rights reserved.