gpt4 book ai didi

c++ - 无法使用 ostream 输出 C++ 输出 vector

转载 作者:行者123 更新时间:2023-11-28 01:48:16 26 4
gpt4 key购买 nike

你好,我想知道我是否可以得到一些帮助来解决我在 C++ 中打印出 vector 内容的问题

我试图以特定顺序在一个或两个函数调用中输出一个类的所有变量。但是我在遍历 vector 时收到一个奇怪的错误

我收到的错误是错误

 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,然后是proposer,然后是关键字,然后是内容。

最佳答案

这是因为 printIdeaconst方法。 const不允许方法修改其成员,因此 keywords.begin()返回 vector<string>::const_iterator ,不是普通的 (vector<string>::iterator)。您应该更改 it 的类型:

vector<string>::iterator it;

到:

vector<string>::const_iterator it;

拥有兼容的类型。

或者,如果您有一个支持 C++11 的编译器,您可以让编译器为您解决:

auto it = keywords.begin()

关于c++ - 无法使用 ostream 输出 C++ 输出 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com