zoukankan      html  css  js  c++  java
  • map实现单词转换程序的例子

    代码来源于c++ primer 10.3

    功能:已知一个一一对应的词典,求一小段文档对应的“翻译”

    词典如下:

    A a B b C c D d E e
    

     输入:

    D D E
    

     代码:

    //需要两个文件,一个是字典文件,一个是输入文件
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <utility>
    #include <map>
    #include <string>
    
    using namespace std;
    ifstream& open_file(ifstream &in, const string &file)
    {
            in.close();
    		in.clear();
            in.open(file.c_str());
    		return in;
     }
    int main(int argc,char ** argv)
    {
    	map<string, string> trans_map;
    	string key, value;
    	if (argc != 3)
    	{
    		throw runtime_error("wrong number of arguments ,we need an dictionary.txt and an input.txt");
    	}
    	ifstream map_file;
    	if (!open_file(map_file,argv[1]))
    	{
    		throw runtime_error("no dictionary file");
    	}
    	while (map_file >> key >> value)
    	{
    		trans_map.insert(make_pair(key, value));
    	}
    	ifstream input;
    	if (!open_file(input, argv[2]))
    	{
    		throw runtime_error("no input file");
    	}
    	string line;
    	while (getline(input, line))
    	{
    		istringstream stream(line);
    		string word;
    		bool firstword = true;
    		while (stream >> word)
    		{
    			map<string, string>::const_iterator map_it = trans_map.find(word);
    			if (map_it != trans_map.end())
    			{
    				word = map_it->second;
    			}
    			if (firstword)
    			{
    				firstword = false;
    			}
    			else
    			{
    				cout << " ";
    			}
    			cout << word;
    		}
    		cout << endl;
    	}
    	return 0;
    }
    

     操作,makefile:

    edit:trans_words.o
    	g++ -o edit trans_words.o
    trans_words.o:trans_words.cpp
    	g++ -c trans_words.cpp
    
    clean: 
    	rm trans_words.o
    

     run.sh

    #!/bin/sh
    make
    ./edit dictionary.txt input.txt
    

     结果:

    d d e
    
  • 相关阅读:
    Flink 多流转换算子
    Flink 基本算子map、keyBy、sum、reduce
    Scala 调用方法时加不加小括号
    Hive rank函数开窗
    Hive 窗口函数
    Scala 集合Map的基本操作
    LOJ#2402. 「THUPC 2017」天天爱射击 / Shooting 整体二分+树状数组
    LOJ#106. 二逼平衡树 树套树
    LOJ#2340. 「WC2018」州区划分
    LOJ#2304. 「NOI2017」泳池(70pts) dp
  • 原文地址:https://www.cnblogs.com/simayuhe/p/5863670.html
Copyright © 2011-2022 走看看