#include <iostream>
#include <list>
using namespace std;
struct DATA
{
int d;
int d2;
};
int main()
{
DATA d1;
d1.d = 100;
d1.d2 = 200;
list<DATA> ld;
ld.push_back(d1);
ld.remove(d1);
}
Compiling the above code gives following error:
1>------ Build started: Project: ConsoleApplication2_List, Configuration: Debug Win32 ------
1>ConsoleApplication2_List.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1603,65): error C2676: binary '==': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
1> with
1> [
1> _Ty=DATA
1> ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1602): message : while compiling class template member function 'auto std::list<DATA,std::allocator<DATA>>::remove(const _Ty &)'
1> with
1> [
1> _Ty=DATA
1> ]
1>C:\TestCode\ConsoleApplication2_List\ConsoleApplication2_List\ConsoleApplication2_List.cpp(17): message : see reference to class template instantiation 'std::list<DATA,std::allocator<DATA>>' being compiled
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1614,1): error C2451: conditional expression of type 'void' is illegal
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1614,22): message : Expressions of type void cannot be converted to other types
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\include\list(1603): message : see reference to function template instantiation 'auto std::list<DATA,std::allocator<DATA>>::remove_if<std::list<DATA,std::allocator<DATA>>::remove::<lambda_c489c5225c742bd5c5073b600e1d767b>>(_Pr1)' being compiled
1> with
1> [
1> _Pr1=std::list<DATA,std::allocator<DATA>>::remove::<lambda_c489c5225c742bd5c5073b600e1d767b>
1> ]
1>Done building project "ConsoleApplication2_List.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have created a C++ program which uses list
containing a custom type struct data
, it works fine for adding data, but when I call the remove
function the compiler issues the above errors.
How do I solve this issue?
As the error message tells you, you need an
operator==
to check equality. This is how theremove
function will know which elements to remove.Edit
As pointed out by Jens it's generally a good idea to define operands as free functions. This is due to the fact that both the right-hand side and left-hand side of the operator would be able to implicitly convert to the correct type. Compared to a member function where only the right-hand side of the operator would be able to implicitly convert.
In this specific case it wouldn't make a difference, but in general it can be a good rule of thumb.