Boost库容器

1.Boost.Array

1)boost.array和std.vector基本上有相同的操作,只不过boost::array是定长的。

2)boost.array可以用=直接赋值

#include "pch.h"
#include <iostream>
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
using namespace std;

typedef boost::array<string, 5> arrName;
int main()
{
	arrName a;
	a = { "zhangsan", "lisi", "wanger", "mazi", "bajie" };
	for (auto item : a)
	{
		cout << item << " ";
	}
	cout << endl;
	a[4] = "sunwukong";
	for (auto item : a)
	{
		cout << item << " ";
	}
	cout << endl;
	system("pause");
}

2.Boost.Unordered

1 )Boost.Unordered 不要求其中的元素是可排序的, 因为它不会做出排序操作。 在排序操作无足轻重时(或是根本不需要), Boost.Unordered 就很合适了。包括boost::unordered_set, boost::unordered_multiset, boost::unordered_map 和 boost::unordered_multimap四类。

2)为了能够快速的查找元素, 我们需要使用 Hash 值。 比如 std::set 要求其中的元素都要是可比较的,而 boost::unordered_set 要求其中的元素都要可计算 Hash 值。所以boost.unordered_set中的key是可以重复的。

3)对于一些自定义的类型,可能是不可hash的,但是可以自己定义其hash函数,其标签必须为hash_value()

typedef boost::unordered_multimap<string, int> NameAge;
typedef boost::unordered_multimap<std::string, int>::value_type NameAgeValue;
int main()
{
	NameAge na;
	na.insert(NameAgeValue("haha", 1));
	na.insert(NameAgeValue("haha", 2));
	na.insert(NameAgeValue("haha", 3));
	for (auto item : na)
	{
		std::cout << item.first << "  :  " << item.second << std::endl;
	}

	system("pause");
}

3.Boost.MultiIndex

跳过。。。

4.Boost.Bimap

Bimap这个容器十分类似于 std::map, 但他不仅可以通过 key 搜索, 还可以用 value 来搜索。(第一次我看成了Bitmap)。

1)实现就是用到两组map,一个是<key, value>,一个是<value, key>

2)如果定义是boost::bimap<string, int>的话,那么bimap中key和value都要求是唯一的,只有key,value定义成

boost::bimaps::multiset_of<type>,才可以允许有重复的情况。

#include "pch.h"
#include <iostream>
#include <boost/bimap/multiset_of.hpp> 
#include <boost/bimap.hpp> 
#include <string> 
#include <boost/typeof/typeof.hpp>
using namespace std;

int main()
{
	//typedef boost::bimap<string, int> bimap;

	typedef boost::bimap<boost::bimaps::multiset_of<std::string>, boost::bimaps::multiset_of<int>> bimap;
	bimap persons;

	persons.insert(bimap::value_type("Boris", 31));
	persons.insert(bimap::value_type("Boris", 31));
	persons.insert(bimap::value_type("Caesar", 33));

	for (bimap::iterator it = persons.begin(); it != persons.end(); ++it)
	{
		std::cout << it->left << " is " << it->right << " years old." << std::endl;
	}
		
	system("pause");
}

发布了27 篇原创文章 · 获赞 9 · 访问量 4907

猜你喜欢

转载自blog.csdn.net/weixin_41761608/article/details/92648638