map应用实例二

本文介绍了如何利用C++标准库中的multimap来实现简单的英语到德语的词汇对照字典,并展示了如何查找包含特定英文单词的所有条目及特定德语翻译对应的英文单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将multimap当作字典

#include<iostream>
#include<map>
#include<string>
#include<iomanip>

using namespace std;

void main()
{
	typedef multimap<string,string> StrStrMMap;
	StrStrMMap dict;
	dict.insert(make_pair("day" , "Tag"));
	dict.insert(make_pair("strange" , "fremd"));
	dict.insert(make_pair("car" , "Auto"));
	dict.insert(make_pair("smart" , "elegant"));
	dict.insert(make_pair("trait" , "Merkmal"));
	dict.insert(make_pair("smart","raffiniert"));
	dict.insert(make_pair("strange" , "seltsam"));
	dict.insert(make_pair("clever" , "raffiniert"));

	StrStrMMap::iterator pos;
	cout.setf(ios::left,ios::adjustfield);
	cout<<' '<<setw(10)<<"English"<<"German"<<endl;
	cout<<setfill('-')<<setw(20)<<" "<<setfill(' ')<<endl;

	for(pos = dict.begin(); pos != dict.end(); ++pos){
		cout<<' '<<setw(10)<<pos->first.c_str()
			<<pos->second<<endl;
	}
	cout<<endl;

	string word("smart");
	cout<<word<<":"<<endl;
	for(pos=dict.lower_bound(word); pos != dict.upper_bound(word); ++pos){
		cout<<"\t"<<pos->second<<endl;
	}

	word=("raffiniert");
	cout<<word<<":"<<endl;
	for(pos=dict.begin(); pos !=dict.end(); ++pos){
		if(pos->second==word){
			cout<<"\t"<<pos->first<<endl;
		}
	}
}

搜索具有某特定实值(values)的元素:
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;

template <class K,class V>
class value_equal{
private:
	V value;
public:
	value_equal(const V& v):value(v){}

	bool operator()(pair<const K,V> elem){
	return elem.second==value;
	}
};

void main()
{
	typedef map<float,float> FloatFloatMap;

	FloatFloatMap coll;
	FloatFloatMap::iterator pos;

	coll[1]=7;
	coll[2]=4;
	coll[3]=2;
	coll[4]=3;
	coll[5]=6;
	coll[6]=1;
	coll[7]=3;

	pos=coll.find(3.0);
	if(pos != coll.end())
	{
		cout<<pos->first<<":"<<pos->second<<endl;
	}

	pos=find_if(coll.begin(),coll.end(),value_equal<float ,float>(3.0));

	if(pos != coll.end())
		cout<<pos->first<<":"<<pos->second<<endl;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值