【发布时间】:2018-11-01 23:54:53
【问题描述】:
我编写了一个代码,它必须遍历一个向量并打印它的内容。我收到一个错误:
dfs.cpp:45:16: error: no match for ‘operator*’ (operand type is ‘const traits’) std::cout
但是,迭代适用于 char
类型的向量#include<iostream>
#include<list>
#include<vector>
#include<stdio.h>
using namespace std;
struct traits
{
int x;
bool visit;
std::list<int> friends;
};
int main()
{
cout << "Enter the number of employees: " << endl;
int noOfEmployees, noOfFriends;
cin>>noOfEmployees;
std::vector<traits> employees;
int i = 0; int j;
while(noOfEmployees--){
traits v;
v.x = i;
cout << "Enter the no of friends: " << endl;
cin >> noOfFriends;
while(noOfFriends--){
cin>>j;
v.friends.push_back(j);
}
v.visit = false;
employees.push_back(v);
}
std::vector<char> path;
path.push_back('a');
path.push_back('l');
path.push_back('i');
path.push_back('a');
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i){
std::cout << *i << ' ';
}
for(std::vector<traits>::iterator v = employees.begin(); v != employees.end(); ++v){
std::cout<<*v<<endl;
}
}
我看到的答案很少,但我想在没有运算符重载的情况下做到这一点,什么是正确或更多的 C++-nic 方式?
【问题讨论】:
-
traits需要重载operator<<,或者自己打印出traits的内容。 -
为什么你刚刚创建的类型会有一个内置的
operator<<?char是语言的一部分,当然支持打印出来。 -
标准容器不存在,你必须自己写一个重载。
-
提供有效的代码并为您未显示的代码提供错误消息没有多大意义。请提供minimal reproducible example。谢谢。