自定义类对象的向量的std::find的返回值

return value of std::find of an vector of custom class objects

本文关键字:find 返回值 std 向量 对象 自定义      更新时间:2023-10-16

我想处理std::find的返回值,但它不会编译。

错误:'it=__gnu_cxx::operator!=>中的'operator='不匹配(((const__gnu_cxx::__normal_iterator>)(&std::find&lt__gnu_cxx::__normal_iterator>,Dummy>(dummylist.std::vector<_Tp,_Alloc>:begin>(),dummylist.std:vector&lt_Tp,_Alloc>::end>(),((const Dummy)(&Dummy(tempArray[0])))),((常量__gnucxx::__normal_iterator>)(&dummylist.std::vector<_Tp,_Alloc>:结束())

#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#define SIZEDATASET 1
using namespace std;
class Dummy
{
public:
Dummy(int Name)
{
this->Name = Name;
this->v0 = 0;
cout << "Hello, im new " << this->Name << endl;
}
~Dummy()
{
cout << "Im done " << this->Name << endl;
}
int Name;
int v0;
};
bool operator== (const Dummy &D0, const Dummy &D1)
{
return D0.Name == D1.Name;
}

void printClass(vector<Dummy>:: iterator D)
{
cout << "Name: " << (D)->Name << endl;
cout << "v0: " << (D)->v0 << endl;
return;
}
int main()
{
string str0 = "1;3;2;2;2;4;";
string str1 = ";";
string str2;
int ende = 0;
int start = 0;
int length = 0;
int tempArray[SIZEDATASET] = {0};
int _switch = 0;
int i;
vector<Dummy> dummylist;
vector<Dummy>:: iterator it;
Dummy *DummyTemp;

while((unsigned int)(ende = str0.find(str1,ende))!= std::string::npos)
{
length = ende - start;
str2 = str0.substr(start,length);
ende+= str1.size();
start=ende;
tempArray[_switch]= atoi(str2.c_str());
_switch++;
if((_switch%=SIZEDATASET) == 0)
{
for(i=0; i<SIZEDATASET; i++)
{
cout << tempArray[i] << " ";
}
cout << endl;

/*this line*/ if((it = find(dummylist.begin(),dummylist.end(),Dummy(tempArray[0])) != dummylist.end())) /* why u not work?*/
{
cout << "match " << endl;
it->v0++;
}
else
{
cout << "no match" << endl;
dummylist.push_back(Dummy(tempArray[0]));
DummyTemp = &(dummylist.back());
DummyTemp->v0++;
}
}
}
it = dummylist.begin();
while(it != dummylist.end())
{
printClass(it);
it++;
}
dummylist.clear();

return 0;
}

稍后,程序将接收一个数据字符串(str0),将其剪切并存储在临时(tempArray)中。然后我检查(使用find)是否已经获得了具有相同名称的集合数据(tempArray[0]表示数据集的名称)。如果不是这样的话,我会用数据创建一个新的类,并将其存储在向量(dummylist)中。如果我在向量中找到了一个同名的数据集,我想使用find()的返回值来更改向量中现有类的值。

函数find()返回一个迭代器,而"it"是迭代器之一,所以我不知道为什么会出现错误。

对不起我的英语。

谨致问候,多米尼克

编辑:注意,我并没有像这篇文章中那样与find()本身作斗争。

if语句的方括号错误:您试图分配比较操作的结果,而不是比较分配的结果。更改:

if((it = find(dummylist.begin(),dummylist.end(),Dummy(tempArray[0])) != dummylist.end()))

收件人:

if((it = find(dummylist.begin(),dummylist.end(),Dummy(tempArray[0]))) != dummylist.end())