[英]C++ How to print contents of composite vector
我讀了這篇文章如何打印出向量的內容? ,它的一個漂亮答案是按以下方式打印向量的內容
std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, " "));
它工作得很好。 但是如果我的向量的類型為vector<pair<int, struct node>>
該怎么辦? 如何使用上述方法打印此矢量?
我試過了
std::copy(path.begin(), path.end(), std::ostream_iterator<pair<int, struct node>>(std::cout, " "));
我正在收到巨大的錯誤轉儲,以下幾行
在/usr/include/c++/4.9/iterator:64:0包含的文件中,
來自dijkstra.cpp:8:
/usr/include/c++/4.9/ostream:548:5:注意:模板std :: basic_ostream&std :: operator <<(std :: basic_ostream&,const unsigned char *)
運算符<<(basic_ostream&__out,const unsigned char * __s)^
/usr/include/c++/4.9/ostream:548:5:注意:模板參數推導/替換失敗:
在/usr/include/c++/4.9/iterator:66:0中包含的文件中,從dijkstra.cpp:8中包含:
/usr/include/c++/4.9/bits/stream_iterator.h:198:13:注意:無法將'__value'(類型'const std :: pair')轉換為'const unsigned char *'* * M_stream << __value;
無法弄清楚。 有什么幫助嗎?
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <utility>
struct node
{
private:
int x;
friend std::ostream& operator << (std::ostream& o, const node & n);
};
std::ostream& operator << (std::ostream& o, const node & n)
{
return o << n.x;
}
std::ostream& operator << (std::ostream& o, const std::pair<int, struct node> & p)
{
return o << p.first<< " "<<p.second;
}
int main()
{
std::vector<std::pair<int, struct node> > path;
std::copy(path.begin(), path.end(), std::ostream_iterator<std::pair<int, struct node> >(std::cout, " "));
}
您必須重載<<
以打印出pair<int, struct node>
,還必須重載<<
以打印出node
。
我在上面舉了一個例子。 您必須根據需要更改node
的實現以及node
的重載<<
。
一對沒有默認輸出,因此您需要為此聲明operator<<
:
std::ostream& operator<<( std::ostream& os, const pair<int, struct node>& obj )
{
os << obj.first;
// here, you need to output obj.second, which is a node object
// Possibly, you can define a operator<< for a struct node and then simply do:
// os << ";" << obj.second;
return os;
}
觀看現場演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.