map pair 例子

来源:互联网 发布:遇到淘宝差评师怎么办 编辑:程序博客网 时间:2024/05/29 11:32
typedef pair<int, char*> Element;
typedef map<int, char*> Container;


int main()
{
Container contin;
for ( int ix = 0; ix < 10; ++ix )
{
char* p = new char[16];
sprintf_s(p, 16, "element %d \0", ix );
Element elem( ix, p );
contin.insert( elem );
}


Container::const_iterator ptr;
ptr = contin.find(1);
if ( ptr != contin.end() )
{
cout<< " find key 1" <<endl;
}


Container::iterator begin = contin.begin();


while ( begin != contin.end() )
{
cout<< (*begin).first << "element value: " << (*begin).second <<endl;
delete [](*begin).second;
(*begin).second = NULL;
begin++;
}
return 0;

}


附上map的相应的接口说明

  begin() 返回指向map头部的迭代器

  clear() 删除所有元素

  count() 返回指定元素出现的次数

  empty() 如果map为空则返回true

  end() 返回指向map末尾的迭代器

  equal_range() 返回特殊条目的迭代器对

  erase() 删除一个元素

  find() 查找一个元素

  get_allocator() 返回map的配置器

  insert() 插入元素

  key_comp() 返回比较元素key的函数

  lower_bound() 返回键值>=给定元素的第一个位置

  max_size() 返回可以容纳的最大元素个数

  rbegin() 返回一个指向map尾部的逆向迭代器

  rend() 返回一个指向map头部的逆向迭代器

  size() 返回map中元素的个数

  swap() 交换两个map

  upper_bound() 返回键值>给定元素的第一个位置

  value_comp() 返回比较元素value的函数


原创粉丝点击