stout代码分析之九:c++11容器新特性

  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(1, "one");
  for(auto mit : d)
  {
    std::cout << mit.first << ":" << mit.second << std::endl;
  }
  return 0;
}

    容器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 0;
}

  容器初始化和遍历 

#include <map>
#include <string>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> a = {1, 2, 3};
  std::map<int, std::string> b = {{1, "one"}, {2, "two"}, {3, "three"}};
  
  for(auto& elem : a)
    std::cout << elem << std::endl;

  for (auto& kv : b)
    std::cout << kv.first << " : " << kv.second << std::endl;

  return 0;
}
posted @ 2016-09-20 08:21  后端技术小屋  阅读(392)  评论(0编辑  收藏  举报