STL---下一个排列

#include "iostream"
#include "algorithm"
using namespace std;


int main()
{
    int a[3] = {3, 1, 2};
    sort(a, a+3);     //从小到大排序, 如果不排序,则得不到全部排列结果
    do
    {
        for(int i=0; i<3; i++)
            cout << a[i];
        cout << endl;
    }while(next_permutation(a, a+3));   //下一个排列
    return 0;
}

这里写图片描述


#include "iostream"
#include "algorithm"
#include "set"
using namespace std;
int main()
{
    set<int> s;
    s.insert(4);
    s.insert(3);
    s.insert(2);
    s.insert(1);
    set<int>::iterator it;

    do
    {
        for(it=s.begin(); it!=s.end(); it++)
            cout << (*it) << " ";
        cout << endl;
    }while(next_permutation(s.begin(), s.end()));

    return 0;
}

这里写图片描述

### C++ STL Map 的基本用法 `std::map` 是 C++ 标准模板库 (STL) 提供的一种关联容器,它基于红黑树实现[^3]。这种数据结构允许存储键值对,并自动按照键的顺序排列。以下是 `std::map` 的一些核心功能及其使用方法: #### 创建和初始化 可以创建一个空的 `std::map` 或者通过列表初始化器来填充初始值。 ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap; // 创建一个空 map // 使用列表初始化器 std::map<char, int> anotherMap = { {'a', 1}, {'b', 2} }; return 0; } ``` #### 插入元素 可以通过多种方式向 `std::map` 中插入新元素。 ```cpp myMap[1] = "one"; // 方括号操作符会插入或更新已存在的键 myMap.insert({2, "two"}); // insert 方法显式插入一对 key-value myMap.emplace(3, "three"); // emplace 更高效地构建并插入对象 ``` #### 查找元素 查找特定键是否存在以及获取对应的值是一个常见需求。可以利用成员函数 `find()` 来完成此任务[^2]。 ```cpp auto it = myMap.find(2); if(it != myMap.end()) { std::cout << "Key found: " << it->first << ", Value: " << it->second << '\n'; } else { std::cout << "Key not found\n"; } ``` #### 删除元素 删除指定键的条目或者清除整个映射都可以轻松做到。 ```cpp myMap.erase(1); // 移除键为 1 的元素 myMap.clear(); // 清空所有元素 ``` #### 遍历 遍历所有的键值对通常采用迭代器来进行。 ```cpp for(const auto& pair : myMap){ std::cout << pair.first << ": " << pair.second << "\n"; } ``` #### 自定义比较函数 为了更灵活地控制如何排序键,可以提供自定义的比较逻辑给 `std::map` 构造函数[^1]。 ```cpp struct GreaterThanComparator{ bool operator()(const int lhs, const int rhs)const{ return lhs > rhs;} }; std::map<int,std::string,GreaterThanComparator> descendingMap; descendingMap[5]="five"; descendingMap[1]="one"; // 输出将按降序显示因为用了自定义比较器 for(auto &p : descendingMap){ std::cout<< p.first <<": "<< p.second<<"\n"; } ``` ### 性能考量 由于内部采用了平衡二叉搜索树的数据结构,因此大多数涉及单个元素的操作时间复杂度均为 O(log n)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值