【发布时间】:2021-11-03 06:40:48
【问题描述】:
我编写了一个程序来从向量中获取对象的引用计数。我将对象存储在列表中,其中有来自向量的计数。我不想按排序顺序存储它们,这就是我使用列表存储的原因。但是在编译时失败并出现错误
"‘Item’ is not derived from ‘const __gnu_cxx::__normal_iterator<_IteratorL, _Container>’".
我不确定错误。亲爱的朋友,请您回答我以下问题。
- 如何解决此错误?
- 如何使用任何容器来存储它们及其引用计数,但不是按排序顺序,而是按向量中的到达顺序存储它们? 请使用以下链接查看源文件。
#include <iostream>
#include <string>
#include <list>
#include <vector>
#include<bits/stdc++.h>
using namespace std;
class Item
{
public:
int count;
string name;
Item(){};
Item(string str, int cnt)
{
name = str;
count = cnt;
};
};
string func(vector<string>& vec)
{
list<Item> lst;
list<Item>:: iterator it;
for(int i=0; i<vec.size(); i++)
{
it = find(lst.begin(), lst.end(), vec[i]);
if(it != lst.end())
{
it->count++;
}
else
{
lst.push_back({vec[i], 1});
}
}
for(it = lst.begin(); it != lst.end(); it++)
{
if(it->count == 1)
return it->name;
}
return "";
}
int main()
{
vector <string> vec = {"saint", "catacana", "saint", "ant"};
cout<<"String is "<<func(vec);
return 0;
}
【问题讨论】:
-
请将您的代码缩减为minimal reproducible example。
-
失败的行是
it = find(lst.begin(), lst.end(), vec[i]);——您试图在Items 的列表中查找字符串,但编译器不知道如何将字符串与项目进行比较。 -
这是 GCC 所说的:
error: no match for 'operator==' (operand types are 'Item' and 'const std::__cxx11::basic_string<char>')。这就是 Clang 所说的:error: invalid operands to binary expression ('Item' and 'const std::basic_string<char>'). -
Dratenik 发布了正确答案。再加上一些小事情:首先,考虑为构造函数使用初始化列表。其次,如果它什么都不做,则不需要定义默认构造函数。它是默认创建的(有例外,但它们不适用于这种情况)。最后,不要使用全局
using namespace std