首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

快速搜索C++中排序的字符串列表

快速搜索C++中排序的字符串列表可以使用STL库中的std::setstd::map容器。这两个容器都是基于红黑树实现的,它们可以快速地进行插入、删除和查找操作。

std::set是一个关联容器,它存储的元素是唯一的,并且已经按照排序顺序排列。可以使用std::setlower_boundupper_bound成员函数进行快速查找。

std::map是一个关联容器,它的键值对是唯一的,并且已经按照键的排序顺序排列。可以使用std::maplower_boundupper_bound成员函数进行快速查找。

以下是一个使用std::set的示例代码:

代码语言:c++
复制
#include<iostream>
#include <set>
#include<string>

int main() {
    std::set<std::string> strings = {"apple", "banana", "cherry", "date", "fig"};

    std::string target = "cherry";
    auto it = strings.lower_bound(target);
    if (it != strings.end() && *it == target) {
        std::cout << "Found "<< target<< std::endl;
    } else {
        std::cout << "Not found"<< std::endl;
    }

    return 0;
}

以上代码会输出Found cherry,因为cherry在字符串列表中。

以下是一个使用std::map的示例代码:

代码语言:c++
复制
#include<iostream>
#include <map>
#include<string>

int main() {
    std::map<int, std::string> strings = {{1, "apple"}, {2, "banana"}, {3, "cherry"}, {4, "date"}, {5, "fig"}};

    int target_key = 3;
    auto it = strings.lower_bound(target_key);
    if (it != strings.end() && it->first == target_key) {
        std::cout << "Found " << it->second<< std::endl;
    } else {
        std::cout << "Not found"<< std::endl;
    }

    return 0;
}

以上代码会输出Found cherry,因为cherry在字符串列表中。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

21分55秒

10_尚硅谷_Vue_列表的搜索和排序

3分59秒

06、mysql系列之模板窗口和平铺窗口的应用

领券