C ++ set 運算符==是C ++中set 的非成員重載函數(shù)。此功能用于檢查兩組集合是否相等。
注意:集合對象之間的比較是基于元素的成對比較。如果兩個集合具有相同數(shù)量的元素,并且它們對應的元素具有相同的值,則兩個集合是相等的。否則它們是不相等的。
template <class T, class Compare, class Alloc> bool operator== ( const set<T,Compare,Alloc>& lhs, const set<T,Compare,Alloc>& rhs );
lhs:第一個設(shè)置的對象。
rhs:第二個對象。
如果set對象的左側(cè)等于set對象的右側(cè),則返回true,否則為false。
如果lhs和rhs的大小不同,則復雜度將保持不變。
否則,最大長度為lhs和rhs。
沒有變化。
可以訪問容器lhs和rhs。
同時訪問未修改集合對象的元素始終是安全的,這意味著它們的元素是不可變的。
此函數(shù)不會引發(fā)異常。
讓我們看一個簡單的示例來檢查兩個集合是否相等:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<char> m1;
set<char> m2;
if (m1 == m2)
cout << "兩個集合是相等的。" << endl;
m1.emplace('a');
//在集合m1中添加元素之后
if (!(m1 == m2))
cout << "兩個集合不相等。" << endl;
return 0;
}輸出:
兩個集合是相等的。 兩個集合不相等。
在上面的示例中,集合m1和m2為空。因此,operator ==將返回true,并且在集合m1中添加一個元素后,m1的大小將不同于m2的大小。因此,它將返回false。
讓我們看一個簡單的實例:
#include <set>
#include <iostream>
int main ()
{
using namespace std;
set <int> m1, m2, m3;
int i;
for (i = 0; i <3; i ++)
{
m1.insert (i);
m2.insert (i * i);
m3.insert (i);
}
if (m1 == m2)
cout << "集合m1和m2是相等的。" << endl;
else
cout << "集合m1和m2不相等。" << endl;
if (m1 == m3)
cout << "集合m1和m3是相等的。" << endl;
else
cout << "集合m1和m3不相等。" << endl;
return 0;
}輸出:
集合m1和m2不相等。 集合m1和m3是相等的。
讓我們看一個簡單的實例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set < int > s1 , s2 ;
s1 . insert ( 10 );
s1 . insert ( 20 );
s1 . insert ( 30 );
s2 = s1 ;
cout << ( s1 == s2 ) << endl ;
s2 . insert ( 40 );
cout << ( s1 == s2 ) << endl ;
}輸出:
1 0
在上面的示例中,如果集合s1和s2相等,則它將返回1,否則返回0。
#include <set>
#include <iostream>
using namespace std;
int main ()
{
set<string> m2;
typedef set<string> login;
m2 = {"xyz@123"} ; //stored password
string password;
login m1;
cout<<"---------Login----------"<<endl<<endl;
cout<<"輸入密碼: \n";
cin>> password; // Get value
m1.insert(password); // Put them in set
cout<<"您輸入的密碼: \n";
for (auto it = m1.begin(); it != m1.end(); it++) {
cout << (*it)<< endl;
}
cout<<"系統(tǒng)中存儲的密碼 :\n";
for (auto it = m2.begin(); it != m2.end(); it++) {
cout << (*it)<< endl;
}
if (m1 == m2)
cout << "\nWelcome to your Page..." << endl;
else
cout << "\nIncorrect Password..." << endl;
return 0;
}輸出:
1). ---------Login---------- 輸入密碼: xyz 您輸入的密碼: xyz 系統(tǒng)中存儲的密碼 : xyz@123 Incorrect Password... 2). ---------Login---------- 輸入密碼: xyz@123 您輸入的密碼: xyz@123 系統(tǒng)中存儲的密碼 : xyz@123 Welcome to your Page...
在上面的示例中,有兩組m1和m2。m1包含密碼,第二組m2存儲用戶輸入的密碼。它檢查這兩個集合是否具有相同的元素。如果密碼匹配,則登錄成功,否則登錄失敗。