stout代码分析之九:c++11容器新特性
2024-08-29 13:30:56
stout大量使用了c++11的一些新特性,使用这些特性有利于简化我们的代码,增加代码可读性。以下将对一些容器的新特性做一个总结。主要两方面:
- 容器的初始化,c++11中再也不用手动insert或者push_back来初始化了
- 容器的遍历,c++11中再也不用使用冗长的迭代器遍历了
- 容器的emplace,避免了一次赋值构造操作和一次析构操作
- 增加了unordered_map容器
- 增加了哈希函数std::hash
让我们一睹为快吧:
std::hash
#include <functional>
#include <string>
#include <iostream>
#include <map> int main()
{
std::hash<std::string> str_hash;
std::string a = "foo";
std::string b = "foo";
std::string c = "bar"; std::cout << (str_hash(a) == str_hash(b) ? "hash(a) == hash(b)" : "hash(a) != hash(b)") << std::endl;
std::cout << (str_hash(a) == str_hash(c) ? "hash(a) == hash(c)" : "hash(a) != hash(c)") << std::endl; std::map<int, std::string> d;
d.emplace(, "one");
for(auto mit : d)
{
std::cout << mit.first << ":" << mit.second << std::endl;
}
return ;
}
容器emplace:
#include <vector>
#include <string>
#include <iostream> class A
{
public:
A(const std::string& name) : name_(name)
{
std::cout << "constructor1" << std::endl;
} A(const A& other) : name_(other.name_)
{
std::cout << "constructor2" << std::endl;
} ~A()
{
std::cout << "destructor" << std::endl;
} private:
std::string name_;
}; int main()
{
std::vector<A> a;
a.push_back(A("foo"));
std::cout << "push back finish" << std::endl; a.emplace(a.begin(), "bar");
std::cout << "emplace finish" << std::endl; std::cout << "to exit" << std::endl;
return ;
}
容器初始化和遍历
#include <map>
#include <string>
#include <iostream>
#include <vector> int main()
{
std::vector<int> a = {, , };
std::map<int, std::string> b = {{, "one"}, {, "two"}, {, "three"}}; for(auto& elem : a)
std::cout << elem << std::endl; for (auto& kv : b)
std::cout << kv.first << " : " << kv.second << std::endl; return ;
}
最新文章
- SpringMVC框架下的异常处理
- linux查找进程,查找僵死进程,查找僵死进程并自动杀掉
- WinRAR压缩操作帮助类
- Maven项目导入后打红色X
- MySQL文件目录格式及存放位置
- mysql 异步执行 query //@todo
- mvc深入理解
- JNI开发示例
- Verilog语法基础讲解之参数化设计
- hadoop笔记之MapReduce的应用案例(利用MapReduce进行排序)
- PHP:class static
- 解决laydate时间日期插件定位溢出
- Akka(42): Http:身份验证 - authentication, autorization and use of raw headers
- jquery对象和DOM对象的区别和转换
- Android官方技术文档翻译——清单合并
- java 轻量级同步volatile关键字简介与可见性有序性与synchronized区别 多线程中篇(十二)
- 【js】this问题
- js-基本语法
- 【专栏学习】APM——异步编程模型(.NET不推荐)
- haproxy反向代理环境部署(http和https代理)