STL学习之map容器(1)

map::map

explicit map ( const Compare& comp = Compare(),
               const Allocator& = Allocator() );
template <class InputIterator>
  map ( InputIterator first, InputIterator last,
        const Compare& comp = Compare(), const Allocator& = Allocator() );
map ( const map<Key,T,Compare,Allocator>& x );
(Key, T, Compare and Allocator
map构造函数

构造一个map容器对象,依据下面的构造函数初始化容器内容:

explicit map ( const Compare& comp = Compare(), Allocator& = Allocator() );
默认构造函数:构造一个空的map对象,这个对象没有内容并且大小为0。

template <class InputIterator>
map ( InputIterator first, InputIterator last, const Compare& comp= Compare(), const Allocator& = Allocator() );
    迭代构造函数:在第一个和最后一个之间迭代,设定每个元素序列的拷贝作为容器对象的内容。

map ( const map<Key,T,Compare,Allocator>& x );
     拷贝构造函数:对象初始化为和x对象有着相同的内容和属性。

参数
first, last

     容器序列中的第一个位置和最后一个位置的输入迭代器,范围为[first,last),包括所有的在first和last之间的元素,其中last是容器中最后一个元素的下一个位置。函数模板类型是任意的输入迭代器 的类型。
x
     有着相同的类模板参数(Key,T,Compare and Allocator)的另一个map对象。
comp

    用于严格的弱排序(weak ordering)的比较对象。
   Compare是第三个类模板参数。
unnamed Allocator parameter

    用于替代构造一个新的Allocator对象。
    对于类实例采用默认分配器类模板的版本,这个参数是不相关的。

实例
// constructing maps
#include <iostream>
#include <map>
using namespace std;

bool fncomp (char lhs, char rhs) {return lhs<rhs;}

struct classcomp {
  bool operator() (const char& lhs, const char& rhs) const
  {return lhs<rhs;}
};

int main ()
{
  map<char,int> first;

  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;

  map<char,int> second (first.begin(),first.end());

  map<char,int> third (second);

  map<char,int,classcomp> fourth;                 // class as Compare

  bool(*fn_pt)(char,char) = fncomp;
  map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare

  return 0;
}

map::count

size_type count ( const key_type& x ) const;

计算map中指定key出现的次数,由于map容器中key值是不允许重复的,所以函数实际返回的是:1,指定的key在容器中;0,指定的key不在容器中。

参数

x
           需要搜索的key值。key_type是一个map容器的成员类型,是key的一个别名。

返回值

如果容器中有指定key的元素,返回1,或者返回0。

size_type成员类型是一个无符号的整数类型。

举例

#include <iostream>
#include <map>

using namespace std;

int main()
{
	map<char, int> mymap;
	char c;
	
	mymap['a'] = 101;
	mymap['c'] = 202;
	mymap['f'] = 303;

	for (c='a'; c<'h'; c++)
	{
		cout << c;
		if (mymap.count(c)>0)
		{
			cout << " is an element of mymap." << endl;
		}
		else
		{
			cout << " is not an element of mymap." << endl;
		}
	}
	return 0;
}
执行结果
liujl@liujl-Rev-1-0:~/mycode/STL$ ./map_count 
a is an element of mymap.
b is not an element of mymap.
c is an element of mymap.
d is not an element of mymap.
e is not an element of mymap.
f is an element of mymap.
g is not an element of mymap.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值