C++ std::set find 错误 operator中不能有<=

Posted 软件工程小施同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ std::set find 错误 operator中不能有<=相关的知识,希望对你有一定的参考价值。

下面的没错

#include <iostream>
#include <set>
using namespace std;
 
class stru{
	public:
   	 	stru(int a, int b): x(a), y(b){}
		int x;
   	 	int y;
};
 
bool operator<(const stru& a, const stru& b)    //比较的是x的值
{
    return a.x < b.x;
}
 
int main()
{
    //创建
    set<stru> st;
    
    //插入
    st.insert(stru(9, 40));   //添加成功,因为multiset可以有重复的值,也就是说有x = 10的stru也可以。
    st.insert(stru(9, 41));    //添加成功
	st.insert(stru(10, 42));
	st.insert(stru(10, 43));
	st.insert(stru(11, 44));
    
    //查看
    for (auto it = st.rbegin(); it != st.rend(); it++)   //10-40 9-43 9-45 8-40 7-35 6-30 5-25 4-20 3-15 2-10 1-5 0-0
        cout<<(*it).x<<"-"<<(*it).y<<" ";
    cout<<endl;
	
	// 查找
    auto it = st.find(stru(10, 43));           //和上面一样,只会找x = 9的第一项。
    cout<<it->x<<" "<<it->y<<endl;             // 返回10,42
	
	auto it2 = st.find(stru(11, 43));           //和上面一样,只会找x = 9的第一项。
    cout<<it2->x<<" "<<it2->y<<endl;             // 返回10,42
	
}

如果把operator中的a.x<b.x修改为a.x<=b.x

#include <iostream>
#include <set>
using namespace std;
 
class stru{
	public:
   	 	stru(int a, int b): x(a), y(b){}
		int x;
   	 	int y;
};
 
bool operator<(const stru& a, const stru& b)    //比较的是x的值
{
    return a.x <= b.x;
}
 
int main()
{
    //创建
    set<stru> st;
    
    //插入
    st.insert(stru(9, 40));   //添加成功,因为multiset可以有重复的值,也就是说有x = 10的stru也可以。
    st.insert(stru(9, 41));    //添加成功
	st.insert(stru(10, 42));
	st.insert(stru(10, 43));
	st.insert(stru(11, 44));
    
    //查看
    for (auto it = st.rbegin(); it != st.rend(); it++)   //10-40 9-43 9-45 8-40 7-35 6-30 5-25 4-20 3-15 2-10 1-5 0-0
        cout<<(*it).x<<"-"<<(*it).y<<" ";
    cout<<endl;
	
	// 查找
    auto it = st.find(stru(10, 43));           //和上面一样,只会找x = 9的第一项。
    cout<<it->x<<" "<<it->y<<endl;             // 返回10,42
	
	auto it2 = st.find(stru(11, 43));           //和上面一样,只会找x = 9的第一项。
    cout<<it2->x<<" "<<it2->y<<endl;             // 返回10,42
	
}

set中不能存在相同的元素

 

 

以上是关于C++ std::set find 错误 operator中不能有<=的主要内容,如果未能解决你的问题,请参考以下文章