跳到主要内容

std::set key_comp() 方法

// Const version only
key_compare key_comp() const;

返回比较键的函数对象,它是此容器构造函数参数 comp 的副本。它与 value_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};

auto comp_func = cont.key_comp();

for (int key : cont) {
bool before = comp_func(key, 100);
bool after = comp_func(100, key);
if (!before && !after)
std::cout << key << " equivalent to key 100\n";
else if (before)
std::cout << key << " goes before key 100\n";
else if (after)
std::cout << key << " goes after key 100\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 key_comp() 方法

// Const version only
key_compare key_comp() const;

返回比较键的函数对象,它是此容器构造函数参数 comp 的副本。它与 value_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};

auto comp_func = cont.key_comp();

for (int key : cont) {
bool before = comp_func(key, 100);
bool after = comp_func(100, key);
if (!before && !after)
std::cout << key << " equivalent to key 100\n";
else if (before)
std::cout << key << " goes before key 100\n";
else if (after)
std::cout << key << " goes after key 100\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 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。