📜  在 C++ 中查找 Set 中元素的索引(1)

📅  最后修改于: 2023-12-03 15:23:07.483000             🧑  作者: Mango

在 C++ 中查找 Set 中元素的索引

在 C++ 中,可以使用 set 容器来存储一组有序、独一无二的元素。如果需要在 set 中查找某个特定的元素并返回其索引(即在序列中的位置),可以使用 std::distance 函数和 std::lower_bound 算法来计算。

使用 std::distance 函数和 std::lower_bound 算法

示例代码:

#include <iostream>
#include <set>
#include <algorithm>

int main() {
    std::set<int> s = {1, 2, 3, 4, 5};
    int target_element = 4;

    // 使用 std::lower_bound 算法查找 target_element
    auto it = std::lower_bound(s.begin(), s.end(), target_element);

    if(it != s.end() && *it == target_element) {  // 如果找到了 target_element
        // 使用 std::distance 函数计算 target_element 的索引
        int index = std::distance(s.begin(), it);
        std::cout << "Index of " << target_element << " is " << index << std::endl;
    }
    else {
        std::cout << "Failed to find " << target_element << std::endl;
    }

    return 0;
}

输出:

Index of 4 is 3

上述代码中,首先定义了一个有序、独一无二的 set 容器 s,然后设定需要查找的目标元素 target_element 为 4。接下来,使用 std::lower_bound 算法来查找 target_element 所在的迭代器,并将其赋值给 it 变量。由于 lower_bound 函数返回的是迭代器,因此需要使用 * 解引用操作符来获取迭代器所指向的元素。如果找到了目标元素,则使用 std::distance 函数来计算其索引并输出。否则,输出未找到目标元素的提示信息。

值得注意的是,由于 set 容器是按照元素的大小来排序的,因此使用 std::distance 函数计算的索引与元素在容器中的位置并不一定相同。如果需要查找元素在 set 容器中的确切位置,可以使用 std::find 函数来代替 std::lower_bound 算法,但这样的操作效率会比较低。

将 std::set 转换为 std::vector

由于 std::set 并不是基于下标访问的容器,因此在该容器中查找元素的索引就变得比较困难。不过,可以考虑将 std::set 容器转换为 std::vector 容器,然后使用 std::find 函数来查找元素并返回其索引。

示例代码:

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

int main() {
    std::set<int> s = {1, 2, 3, 4, 5};
    int target_element = 4;

    // 将 std::set 转换为 std::vector
    std::vector<int> v(s.begin(), s.end());

    // 使用 std::find 函数查找 target_element
    auto it = std::find(v.begin(), v.end(), target_element);

    if(it != v.end()) {  // 如果找到了 target_element
        // 使用 std::distance 函数计算 target_element 的索引
        int index = std::distance(v.begin(), it);
        std::cout << "Index of " << target_element << " is " << index << std::endl;
    }
    else {
        std::cout << "Failed to find " << target_element << std::endl;
    }

    return 0;
}

输出:

Index of 4 is 3

上述代码中,首先定义了一个有序、独一无二的 set 容器 s,然后设定需要查找的目标元素 target_element 为 4。接下来,通过将 s 容器中的元素插入到 std::vector 中来完成容器类型的转换。然后,使用 std::find 函数来查找目标元素是否存在,并获取其迭代器作为返回值。最后,使用 std::distance 函数来计算目标元素在 std::vector 中的索引并输出。

需要注意的是,将 std::set 容器转换为 std::vector 容器并不会改变其有序性和独一无二性。当出现重复元素时,std::vector 中只会保留一个,而其余的则会被自动删除。