#include <iostream>
#include <map>
#include <unordered_map>
#include <tuple>
void test1()
{
/* map、mutimap都是安装key进行排序的容器,内部实现是红黑树
插入和搜索的时间复杂度是O(log(size)),区别是map中key不可重复
*/
std::map<int, std::string> map1 = {
{1, "1"},
{3, "3"},
{2, "2"},
};
for (auto &it : map1)
{
std::cout << it.first << ":" << it.second << std::endl;
}
// 无序map
std::unordered_map<int, std::string> unmap = {
{1, "1"},
{3, "3"},
{2, "2"},
};
for (auto &it : unmap)
{
std::cout << it.first << ":" << it.second << std::endl;
}
}
void test2()
{
/*元组三要素:除了自定义结构,tuple可以存储不同类型的数据
1.std::make_tuple:构造元组
2.std::get<index>/<type>:根据位置或类型获取元组元素
3.std::tie:元组拆分,缺点需要事先知道元素的个数和对应的具体类型
*/
std::string nm;
int age;
double grade;
auto tp = std::make_tuple("zhangsan", 10, 99.5);
// 位置获取元素
std::cout<<std::get<0>(tp)<<std::endl;
std::cout<<std::get<1>(tp)<<std::endl;
// 也可以通过类型获取元素
std::cout<<std::get<double>(tp)<<std::endl;
// 元组拆包
std::tie(nm, age, grade) = std::make_tuple("lisi", 20, 60.5);
std::cout<<nm<<","<<age<<"," <<grade<<std::endl;
}
int main()
{
test1();
test2();
return 0;
}
C++新特性unordered_map和tuple
最新推荐文章于 2025-03-25 22:59:00 发布