在 C++ 中,list 容器的 merge() 函数用于将另一个 list 容器中的元素合并到当前的 list 容器中。merge() 函数的第二个参数是一个比较函数,用于指定如何对元素进行排序。

以下是一个示例,演示了如何使用 merge() 函数的第二个参数:

#include <iostream>
#include <list>

// 比较函数,用于指定元素的排序方式
bool compfunction(int a, int b) {
    return a < b;
}

int main() {
    std::list<int> list1 = {1, 3, 5};
    std::list<int> list2 = {2, 4, 6};

    // 使用 merge() 函数将 list2 中的元素合并到 list1 中,并按照 compfunction 的排序方式进行排序
    list1.merge(list2, compfunction);

    // 输出合并后的 list1
    for (auto it = list1.begin(); it != list1.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

输出结果为:

1 2 3 4 5 6

在上面的示例中,我们定义了一个比较函数 compfunction,用于指定元素的排序方式。然后,我们创建了两个 list 容器 list1 和 list2,分别包含了一些元素。接下来,我们使用 merge() 函数将 list2 中的元素合并到 list1 中,并按照 compfunction 的排序方式进行排序。最后,我们遍历输出合并后的 list1,可以看到元素已经按照升序排序。

C++ list 容器 merge() 函数的第二个参数使用详解及示例

原文地址: https://www.cveoy.top/t/topic/pcVQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录