问题描述
mySongs
是一个向量,用于存储用户输入的歌曲集合。在 if 语句中,程序将使用用户输入检查向量中的元素。如果匹配,它将从向量中删除该指定值。当我寻找解决方案时,我看到有人建议使用 remove/erase idiom:。但是当我在我的代码中实现时,它继续弹出这个错误C2678 binary '==': no operator found which takes a left - hand operand of type 'Song' (or there is no acceptable conversion)
void deleteSong() {
string songTitle;
cout << "\n\t\tPlease enter the particular song name to remove: ";
cin >> songTitle;
if (songTitle != "") {
for (Song songs : mySongs) {
if (songs.title == songTitle) {
mySongs.erase(find(mySongs.begin,mySongs.end,songs)); //erase an element with value
break;
}
}
}
}
解决方法
这个错误是由于 Song 类没有 == 运算符造成的。这可以通过以下两种方式之一解决
-
如果您可以访问 Song 的源代码,那么 向其添加以下功能。请注意 const 是必要的
bool operator == ( const Song& song) { //Do the comparison code here }
-
如果您无权访问源代码。然后添加如下函数
bool operator == (const Song& song1,const Song& song2) { // Do the comparison code here }
也就是说,你的代码还有一个小问题
擦除函数应该这样调用
mySongs.erase(find(mySongs.begin(),mySongs.end(),songs));
我决定添加一个最小的例子来帮助你。在那个例子中,我假设了 Song 的某个实现,但该实现不一定是你所拥有的
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class Song
{
public:
std::string title;
/* bool operator ==(const Song& other)
{
return this->title == other.title;
}*/
};
bool operator ==(const Song& song1,const Song& other)
{
return song1.title == other.title;
}
std::vector<Song> mySongs={{"ali"},{"ahmed"},{"ali"}};;
void deleteSong() {
string songTitle;
cout << "\n\t\tPlease enter the particular song name to remove: ";
cin >> songTitle;
if (songTitle != "") {
for (const auto& songs : mySongs) {
if (songs.title == songTitle) {
mySongs.erase(find(mySongs.begin(),songs)); //erase an element with value
break;
}
}
}
}
int main() {
// your code goes here
return 0;
}