如何解决类型差异,而使用std::count函数计数项目的数量在向量?



我有一个名为boat_list的结构类型向量Item (vector<Item>),它将保存Items。

我试图使用std::count函数来计数基于从c++中找到的示例代码的项目类型的实例参考:

int mycount = std::count (myvector.begin(), myvector.end(), 20);

,但我得到一个错误,是有关的类型差异:

from /usr/include/c++/7/vector:60,
from Boat.h:1,
from main.cpp:1:
/usr/include/c++/7/bits/predefined_ops.h: In instantiation of ‘bool __gnu_cxx::__ops::_Iter_equals_val<_Value>::operator()(_Iterator) [with _Iterator = __gnu_cxx::__normal_iterator<Item*, std::vector<Item> >; _Value = const int]’:
/usr/include/c++/7/bits/stl_algo.h:3194:12:   required from ‘typename std::iterator_traits<_Iterator>::difference_type std::__count_if(_InputIterator, _InputIterator, _Predicate) [with _InputIterator = __gnu_cxx::__normal_iterator<Item*, std::vector<Item> >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const int>; typename std::iterator_traits<_Iterator>::difference_type = long int]’
/usr/include/c++/7/bits/stl_algo.h:4084:29:   required from ‘typename std::iterator_traits<_Iterator>::difference_type std::count(_IIter, _IIter, const _Tp&) [with _IIter = __gnu_cxx::__normal_iterator<Item*, std::vector<Item> >; _Tp = int; typename std::iterator_traits<_Iterator>::difference_type = long int]’
Boat.h:48:66:   required from here
/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for ‘operator==’ (operand types are ‘Item’ and ‘const int’)
{ return *__it == _M_value; }
~~~~~~^~~~~~~~~~~

这里是我的错误发生的函数:

int type = boat_list.at(i).item_number;
int type_count = count(boat_list.begin(), boat_list.end(), type); //Error occurs here @line 48:66
for (int j = i + 1; j < boat_list.size(); j++) {
if (type = boat_list.at(j).item_number) {
continue;
}

我认为在使用此方法时应该没有错误,因为我使用的是存储在名为item_number的boat_list中的int。问题原因是通过使用一个向量类型的项目?

问题是没有定义对象的operator ==Item种类和类型int错误消息说。

您需要使用算法std::count_if提供比较函数,例如

int type_count = std::count_if( boat_list.begin(), boat_list.end(), 
[&type]( const auto &item )
{
return  item.item_number == type;
} );
比起变量type_count的类型int,最好至少使用类型说明符auto
auto type_count = std::count_if( /*...*/ );

相关内容

最新更新