c++_stl-2


API可访问 cplusplus.com/reference

4. deque容器

deque<int> d

可翻译为双端队列,主要操作与vector类似:

  • push_back(),pop_back(),push_front(),pop_front()
  • front(),back()取头尾元素
  • iterator find(iterator begin, iterator end, value)根据值找索引,找不到则返回end()

5. stack容器

stack<int> s

主要操作:

  • void push(),void pop()
  • bool empty(),常用语句为while( !s.empty()){}
  • s.top()获取栈顶元素

可尝试练习用栈等容器存储指针

6. queue容器

queue<int> q

主要操作和栈相同。

6.1 priority_queue

the first element is always the greatest of the elements it contains.

template <class T, class Container = vector<T>,
  class Compare = less<typename Container::value_type> >
      
/*
std::less
returns whether the its first argument compares less than the second
*/

默认最大优先级队列.

#include<iostream>
using namespace std;
#include "queue" 
#include "functional"

int main(int argc, char *argv[])
{
	priority_queue<int> pq1;
	//priority_queue<int,vector<int>,less<int> > pq2;
	priority_queue<int,vector<int>,greater<int> > pq3;
	
	pq1.push(5);
	pq1.push(3);
	pq1.push(7);
	
	while(pq1.size())
	{
		cout<<pq1.top()<<" ";
		pq1.pop();
	}
	cout<<endl;
	
	pq3.push(5);
	pq3.push(3);
	pq3.push(7);
	while(pq3.size())
	{
		cout<<pq3.top()<<" ";
		pq3.pop();
	}
	
	cin.get();
	return 0;
}
/*
7 5 3
3 5 7
*/

7. List容器

双向链表容器,不能随机存取元素,即不支持[]at();迭代器支持it++,但不支持it+2等随机访问。

一些操作可以查询API

删除

list.clear(),清空

iterator list.erase(iterator begin, iterator end),注意左闭右开,返回后 一元素位置

iterator list.erase(iterator pos)

list.remove(elem)删除所以该值

#include<iostream>
using namespace std;
#include "list" 

int main(int argc, char *argv[])
{
	list<int> l;
	l.push_back(1);
	l.push_back(2);
	l.push_back(3);
	l.push_back(4);
	list<int>::iterator it1 = l.begin();
	list<int>::iterator it2 = l.begin();
	//list<int>::iterator it2 = l.begin() + 3;
	
	it2++;
	it2++;
	
	list<int>::iterator it3 = l.erase(it1,it2);
	it1 = l.begin();
	while(it1 != l.end())
	{
		cout<<*it1<<" ";
		it1++;
	}
	cout<<endl;
	
	cout<<*it3<<endl;
	
	cin.get();
	return 0;
}
/*
3 4
3
*/

8. Set和MultSet

集合采用红黑树这种平衡二叉树数据结构实现,所以:

  • 不能指定插入位置
  • 不能直接存取([],at()
  • 不能直接修改元素,必须先删除再重新添加

set支持唯一键值对,而multiset同一值可以出现多次。

集合自动排序,默认从小到大。

8.1 添加和删除

#include<iostream>
using namespace std;
#include <set>
#include <functional>

int main(int argc, char *argv[])
{
	set<int> set1;
	set<int,greater<int> > set2;
	for(int i = 0 ; i < 3; i++)
	{
		int tmp = rand()%100; 
		set1.insert(tmp);
		set2.insert(tmp);
	}
	for(set<int>::iterator it = set1.begin(); it != set1.end(); it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;
	
	for(set<int>::iterator it = set2.begin(); it != set2.end(); it++)
	{
		cout<<*it<<" ";
	}
	cout<<endl;
	
	while( !set1.empty())
	{
		set1.erase(set1.begin());
	}
	while( !set2.empty())
	{
		set2.erase(set2.begin());
	}
	
	cin.get();
	return 0;
}
/*
34 41 67
67 41 34
*/

对于自定义数据类型,应使用仿函数functor和函数对象。

是使一个类的使用看上去象一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为。less<T>()greater<T>()就是预定义的仿函数,包含在头文件<functional>中。

struct greater
	{	// functor for operator>
	typedef _Ty first_argument_type;
	typedef _Ty second_argument_type;
	typedef bool result_type;

	constexpr bool operator()(const _Ty& _Left, const _Ty& _Right) const
		{	// apply operator> to operands
		return (_Left > _Right);
		}
	};

8.1.1 pair

当比较的值相等时,会插入失败,所以我们要用对组pair类型返回值判断。

This class couples together a pair of values, which may be of different types (T1 and T2). The individual values can be accessed through its public members first and second.

set.insert() return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

#include<iostream>
using namespace std;
#include "set" 
#include "functional"

class Person
{
private:
	int age;
public:
	Person(int age)
	{
		this->age = age;
	}
	int getAge()const
	{
		return this->age;
	}
};

struct greaterPerson {
	bool operator() (const Person& left, const Person& right) const
	{
		return left.getAge() > right.getAge();
	}
};

int main(int argc, char *argv[])
{
	Person p1(11), p2(22), p3(33), p4(11);
	set<Person, greaterPerson> set1;
	Person *persons[4] = { &p1,&p2,&p3,&p4 };
	pair<set<Person, greaterPerson>::iterator, bool> pair;

	for (int i = 0; i < 4; i++)
	{
		pair = set1.insert(*persons[i]);
		if (!pair.second)
		{
			printf("p%d inserted error.\n",i+1);
		}
	}

	for(set<Person, greaterPerson>::iterator it = set1.begin(); it != set1.end(); it++)
	{
		cout << (*it).getAge() << endl;
	}

	cin.get();
	return 0;
}

/*
p4 inserted error.
33
22
11
*/

8.2 查找

iterator set.find(elem),返回指向elem的迭代器,没找到则返回set.end()

int set.count(elem),对于set,返回0或1;对于multiset,可能大于1.

iterator set.lower_bound(elem)返回第一个大于等于elem的迭代器

iterator set.upper_bound(elem)返回第一个大于elem的迭代器

pair<iterator,iterator> equal_range(elem)pair::first is the lower bound of the range (the same as lower_bound), and pair::second is the upper bound (the same as upper_bound). 相当于一个左闭右开区间。

9. Map和MultMap

map是标准的关联式容器,是一个key-value对,也按红黑树规则排序,不能指定位置插入。

添加和删除操作比vector快。

支持[]

map的键是唯一的;multimap相同键可出现多次,所以不支持[]

map<T1,T2> m;

9.1 添加、删除、遍历

几种常用的insert()

  • pair<iterator,bool> insert (const value_type& val);
  • iterator insert (const_iterator position, const value_type& val);
  • void insert (InputIterator first, InputIterator last);
#include<iostream>
using namespace std;
#include "map"
int main(int argc, char *argv[])
{
	map<char,int> mymap;
	mymap.insert ( pair<char,int>('a',100) );
	mymap.insert ( make_pair<char,int>('b',100) );
	pair<map<char,int>::iterator,bool> mypair = mymap.insert ( map<char,int>::value_type('c',100) );
	cout<<"mypair.first:"<<mypair.first->second<<endl;
	
	mymap['d'] = 100;
 	mymap['d'] = 200;
	
	map<char,int>::iterator it = mymap.begin();
	mymap.insert (it, std::pair<char,int>('e',300));
	
	mypair = mymap.insert ( pair<char,int>('a',100) );
	cout<<"mypair.second:"<<mypair.second<<endl;
	
	map<char,int> anothermap;
	anothermap.insert(mymap.begin(),mymap.find('e'));
	
	for (it=anothermap.begin(); it!=anothermap.end(); ++it)
	   	cout << it->first << " => " << it->second << '\n';
 	 
 	while(!mymap.empty())
 	{
	 	map<char,int>::iterator it = mymap.begin();
	 	mymap.erase(it);
 	}
 	while(!anothermap.empty())
 	{
	 	map<char,int>::iterator it = anothermap.begin();
	 	anothermap.erase(it);
 	}
	cin.get();
	return 0;
}



/*
mypair.first:100
mypair.second:0
a => 100
b => 100
c => 100
d => 200
*/

这里注意一下队组配合迭代器的用法:mypair.first->second;

9.2 查找

和[set的查找](#8.2 查找)类似。

iterator map.find(key);

map.count(key);,结尾为0或1;multimap可以大于1.


10. 各个容器比较

每个容器都有默认的构造函数和默认拷贝构造函数。

除了queuestack,每个容器都有可返回迭代器的函数。

大小相关函数:size(),empty()

vectordequelistset/multisetmapmultimap
数据结构单端数组双端数组双向链表二叉树二叉树二叉树
可随机存取1100key可以0
查找速度很慢key快
添加删除尾端双端任何位置---

deque可用于排队系统,而不是vector.

vectordeque的比较:

  • at()vetordeque快,因为后者开头位置不固定;
  • 大量释放操作,vector更快;
  • 头部的快速添加删除是deque的优势。

list可用于乘客的存储。

set可用于存取个人得分。

map可按id存储用户。

[#8.2 查找]:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值