開発環境
- OS X Mavericks - Apple, ときどき
Windows 8.1 + Cygwin64, MinGW (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C++ (プログラミング言語)
- g++(コンパイラ)
C++実践プログラミング (スティーブ オウアルライン (著)、Steve Oualline (原著)、Steve Oualline(原著)、望月 康司(翻訳)、クイープ(翻訳) 、オライリー・ジャパン)のⅤ部(言語のその他の機能)の25章(STL(Standard Template Library))、25.8(プログラミング実習)、実習 25-2.を解いてみる。
その他参考書籍
- C++プログラミング入門 (グレゴリー サティア (著)、ダウグ ブラウン (著)、Gregory Satir (原著)、Doug Brown (原著)、望月 康司 (翻訳)、谷口 功 (翻訳)、オライリージャパン)
実習 25-2.
コード(BBEdit, Emacs)
index.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <set>
#include <map>
#include <algorithm>
static std::ifstream in_file;
static std::ofstream out_file;
static std::map<std::string, std::set<int> > map_index;
static void write_num(const int n)
{
out_file << n << ' ';
}
static void write_word(const std::string word)
{
out_file << word << ' ';
std::map<std::string, std::set<int> >::const_iterator index_loc;
index_loc = map_index.find(word);
std::set<int> set_num = index_loc->second;
std::for_each(set_num.begin(), set_num.end(), write_num);
out_file << '\n';
}
int main(int argc, char *argv[])
{
int n;
std::string word;
std::set<std::string> set_word;
std::map<std::string, std::set<int> >::const_iterator index_loc;
if (argc != 3) {
std::cerr << "Usage: <filename> <filename>\n";
exit (8);
}
in_file.open(argv[1]);
if (in_file.fail()) {
std::cerr << "Unable to open " << argv[1] << '\n';
exit (8);
}
while (!in_file.eof()) {
in_file >> n;
in_file >> word;
set_word.insert(word);
index_loc = map_index.find(word);
if (index_loc == map_index.end()) {
std::set<int> set_num;
set_num.insert(n);
map_index.insert(std::pair<std::string, std::set<int> >(word, set_num));
}
else {
std::set<int> set_num = index_loc->second;
set_num.insert(n);
map_index.erase(word);
map_index.insert(std::pair<std::string, std::set<int> >(word, set_num));
}
}
in_file.close();
out_file.open(argv[2]);
if (out_file.fail()) {
std::cerr << "Unable to open " << argv[2] << '\n';
exit (8);
}
std::for_each(set_word.begin(), set_word.end(), write_word);
out_file.close();
return (0);
}
Makefile
CC=g++
CFLAGS=-g -Wall
SRC=index.cpp
OBJ=index.o
all: index
index: $(OBJ)
${CC} ${CFLAGS} -o index $(OBJ)
index.o: index.cpp
${CC} $(CFLAGS) -c index.cpp
clean:
rm index index.o
入出力結果(Terminal)
$ cat index.dat 5 beta 6 beta 10 alpha 18 beta 20 alpha 30 alpha $ make g++ -g -Wall -c index.cpp g++ -g -Wall -o index index.o $ ./index index.dat index.txt $ cat index.dat 5 beta 6 beta 10 alpha 18 beta 20 alpha 30 alpha $ cat index.txt alpha 10 20 30 beta 5 6 18 $
0 コメント:
コメントを投稿