boost unordered

Boost.Unordered provides the classes boost::unordered_set, boost::unordered_multiset, boost::unordered_map, and boost::unordered_multimap. These classes are identical to the hash containers that were added to the standard library with C++11.

 1. boost::unordered_set

#include <boost/unordered_set.hpp>
#include <string>
#include <iostream>

int main() {
  boost::unordered_set<std::string> set;
  set.emplace("cat");
  set.emplace("shark");
  set.emplace("spider");

  for (const std::string& s : set) {
    std::cout << s << std::endl;
  }

  std::cout << set.size() << std::endl;
  std::cout << set.max_size() << std::endl;

  std::cout << std::boolalpha << (set.find("cat") != set.end()) << std::endl;
  std::cout << set.count("shark") << std::endl;
  return 0;
}

输出为:

spider

shark

cat

3

1152921504606846975

true

1

boost::unordered_set can be replaced with std::unordered_set, boost::unordered_set doesn't differ from std::ordered_set.

2. boost::unordered_map

#include <boost/unordered_map.hpp>
#include <string>
#include <iostream>

int main() {
  boost::unordered_map<std::string, int> map;
  map.emplace("cat", 4);
  map.emplace("shark", 0);
  map.emplace("spider", 8);

  for (const auto& p : map) {
    std::cout << p.first << ";" << p.second << std::endl;
  }

  std::cout << map.size() << std::endl;
  std::cout << map.max_size() << std::endl;

  std::cout << std::boolalpha << (map.find("cat") != map.end()) << std::endl;
  std::cout << map.count("shark") << std::endl;
  return 0;
}

输出为:

spider;8

shark;0

cat;4

3

1152921504606846975

true

1

3. User-defined type with Boost.Unordered

#include <boost/unordered_set.hpp>
#include <string>
#include <cstddef>

struct animal {
  std::string name;
  int legs;
};

bool operator==(const animal& lhs, const animals& rhs) {
  return lhs.name == rhs.name && lhs.legs == rhs.legs;
}

std::size_t hash_value(const animal& a) {
  std::size_t seed = 0;
  boost::hash_value(seed, a.name);
  boost::hash_value(seed, a.legs);
  return seed;
}

int main() {
  boost::unordered_set<animal> animals;

  animals.insert({"cat", 4});
  animals.insert({"shark", 0});
  animals.insert({"spider", 8});

  return 0;
}

Because the hash function of boost::unordered_set doesn't know the class animal, hash values can't be automatically calculate for elements of this type. That's why a hash function must be defined-otherwise the example can't be compiled.

In adddition to defining hash_value(), you need to make sure two objects can be compared using==. That't why the operator== is overloaded for animal.

posted @ 2019-06-13 19:36  c++11  阅读(347)  评论(0编辑  收藏  举报