跳到主要内容

std::set value_comp() 方法

// Const version only
value_compare value_comp() const;

返回比较值的函数对象。它与key_comp()相同。

参数

(无)

返回值

键比较函数对象。

复杂度

常数 - O(1)

异常

(无)

示例

Main.cpp
#include <cassert>
#include <iostream>
#include <set>

// Example module 97 key compare function
struct ModCmp {
bool operator()(const int lhs, const int rhs) const
{
return (lhs % 97) < (rhs % 97);
}
};

int main()
{
std::set<int, ModCmp> cont{1, 2, 3, 4, 5};

// Same behaviour as key_comp()
auto comp_func = cont.value_comp();

const int val = 100;

for (int key : cont) {
bool before = comp_func(key, val);
bool after = comp_func(val, key);
if (!before && !after)
std::cout << key << " equivalent to key " << val << '\n';
else if (before)
std::cout << key << " goes before key " << val << '\n';
else if (after)
std::cout << key << " goes after key " << val << '\n';
else
assert(0); // Cannot happen
}
}
输出
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
本文来源于此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::set value_comp() 方法

// Const version only
value_compare value_comp() const;

返回比较值的函数对象。它与key_comp()相同。

参数

(无)

返回值

键比较函数对象。

复杂度

常数 - O(1)

异常

(无)

示例

Main.cpp
#include <cassert>
#include <iostream>
#include <set>

// Example module 97 key compare function
struct ModCmp {
bool operator()(const int lhs, const int rhs) const
{
return (lhs % 97) < (rhs % 97);
}
};

int main()
{
std::set<int, ModCmp> cont{1, 2, 3, 4, 5};

// Same behaviour as key_comp()
auto comp_func = cont.value_comp();

const int val = 100;

for (int key : cont) {
bool before = comp_func(key, val);
bool after = comp_func(val, key);
if (!before && !after)
std::cout << key << " equivalent to key " << val << '\n';
else if (before)
std::cout << key << " goes before key " << val << '\n';
else if (after)
std::cout << key << " goes after key " << val << '\n';
else
assert(0); // Cannot happen
}
}
输出
1 goes before key 100
2 goes before key 100
3 equivalent to key 100
4 goes after key 100
5 goes after key 100
本文来源于此 CppReference 页面。它可能经过修改以进行改进或满足编辑偏好。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。