您的位置:首页 > 其它

STL学习之map容器(1)

2012-06-21 18:07 369 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: