C ++ set value_comp()函数的作用是:返回一个比较对象。这个函数用于比较两个元素,以检查第一个元素的键是否在第二个元素之前。用来比较value大小。
例如:-对于集合m,如果两个元素e1(k1,d1)和e2(k2,d2)是value_type类型的对象,其中k1和k2是其key_type类型的键,而d1和d2是其data类型的数据value_type,则m value_comp(e1,e2)等效于m key_comp(k1,k2)。
value_compare value_comp() const;
bool-operator (value_type &left, value_type &right);
如果按排序顺序,left的值在前面且不等于right的值,则返回true。
没有
它返回一个值比较函数对象。
不变。
没有变化。
容器被访问。
没有包含元素的访问:同时访问集合的元素是安全的。
如果引发异常,则容器中没有任何更改。
让我们看一下比较元素值的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> c;
set<int>::value_compare comp = c.value_comp();
cout << "比较2和5(1为真,0为假): "<<comp(2, 5) << endl;
cout << "比较8和5(1为真,0为假): "<<comp(8, 5) << endl;
}输出:
比较2和5(1为真,0为假): 1 比较8和5(1为真,0为假): 0
在上面的示例中,因为2小于5,所以comp(2,5)返回true;由于8不小于5,comp(8,5)返回false。
让我们看一个简单的实例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset;
set<int>::value_compare mycomp = myset.value_comp();
for (int i=0; i<=5; i++) myset.insert(i);
cout << "myset 包含:";
int highest=*myset.rbegin();
set<int>::iterator it=myset.begin();
do {
cout << ' ' << *it;
} while ( mycomp(*(++it),highest) );
cout << '\n';
return 0;
}输出:
myset 包含: 0 1 2 3 4
在上面的示例中,最高变量存储myset集合的最后一个元素,并使用该集合的第一个元素(按排序顺序)初始化迭代器。Do-while循环用于打印将在其中运行循环的元素,直到第一个键小于最后一个键为止(为此,它使用名为mycomp的key_comp()函数)。
让我们看一个简单的实例:
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int, less<int> > s1;
set <int, less<int> >::value_compare vc1 = s1.value_comp( );
bool result1 = vc1( 2, 3 );
if( result1 == true )
{
cout << "vc1(2,3)返回true值, "
<< "其中vc1是s1的函数对象。"
<< endl;
}
else
{
cout << "vc1(2,3)返回false值, "
<< "其中vc1是s1的函数对象。"
<< endl;
}
set <int, greater<int> > s2;
set<int, greater<int> >::value_compare vc2 = s2.value_comp( );
bool result2 = vc2( 2, 3 );
if( result2 == true )
{
cout << "vc2(2,3)返回true值, "
<< "其中vc2是s2的函数对象。"
<< endl;
}
else
{
cout << "vc2(2,3)返回false值, "
<< "其中vc2是s2的函数对象。"
<< endl;
}
}输出:
vc1(2,3)返回true值,其中vc1是s1的函数对象。 vc2(2,3)返回false值,其中vc2是s2的函数对象。
让我们看一个简单的示例,以显示key_comp()和value_comp()之间的区别:
#include <set>
#include <iostream>
#include<map>
using namespace std;
int main(){
set<int> myset;
int highest1, highest2;
set<int>::key_compare myCompKeyForSet = myset.key_comp();
set<int>::value_compare myCompValForSet = myset.value_comp();
for (int i=0; i<=5; i++) {
myset.insert(i);
}
highest1=*myset.rbegin();
set<int>::iterator it=myset.begin();
while ( myCompKeyForSet(*it, highest1) ) it++;
cout << "\nhighest1 is " << highest1; // prints 5
highest2 = *myset.rbegin();
it=myset.begin();
while ( myCompValForSet(*it, highest2) ) it++;
cout << "\nhighest2 is " << highest2; // prints 5
return 0;
}输出:
highest1 is 5 highest2 is 5
在上面的示例中,当我们比较key_comp()和value_comp()时,对于这样的集合容器,这两个词是相同的。对于这两种类型的函数,它将返回相同的值。