【发布时间】:2017-05-16 12:19:28
【问题描述】:
您好,我想知道是否可以帮助我解决在 C++ 中打印出向量内容的问题
我试图在一个或两个函数调用中以特定顺序输出一个类的所有变量。但是我在遍历向量时收到一个奇怪的错误
我收到的错误是错误
error C2679: binary '=' : no operator found which takes a right-hand operand of type
'std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>>>' (or there is no acceptable conversion)
我的相关代码如下
ifndef idea
#define idea
using namespace std;
class Idea{
private:
int id;
string proposer, content;
vector<string> keywords;
public:
Idea(int i);
Idea(int i, string pro, string con);
void inputIdea();
int getID(){ return id; };
string getProposer(){ return proposer; };
string getContent(){ return content; };
vector<string> getKeyword();
bool wordSearch(string word);
friend ostream& operator<< (ostream& stream, const Idea& i);
void printIdea(ostream& os)const;
};
bool Idea::wordSearch(string word){
vector<string>::iterator it;
for(it = keywords.begin(); it < keywords.end(); it++){
if (word == *it){
return true;
}
}
if (content.find(word) != string::npos){
return true;
}
return false;
}
void Idea::printIdea(ostream& os)const{
vector<string>::iterator it;
os << "ID: " << id << endl;
os << "Proposer: " << proposer << endl;
os << "keywords: ";
for (it = keywords.begin(); it < keywords.end(); it++){ // error C2679
os << *it << " ,";
}
os << endl << "content: " << content << endl;
}
ostream& operator<<(ostream& os, const Idea& i)
{
i.printIdea(os);
return os;
}
我觉得这很奇怪,因为迭代器函数在代码的不同部分工作。
bool Idea::wordSearch(string word){
vector<string>::iterator it;
for(it = keywords.begin(); it < keywords.end(); it++){
if (word == *it){
return true;
}
}
if (content.find(word) != string::npos){
return true;
}
return false;
}
我希望打印出 id,然后是提议者,然后是关键字,然后是内容。
【问题讨论】:
-
另外,使用
!=而不是<来循环使用迭代器,它允许其他迭代器继续工作。 -
您好,感谢您的回答,经过一个多小时的调查,我实际上能够自己解决错误。我已经从我的重载函数调用中删除了 const 标签。我会记住你的建议,但是学习总是好的。如果它确实对输出有效,将再次回复!
标签: c++ vector operator-overloading ostream