Skip to content

Commit

Permalink
🍻 Finished ch11
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Dec 18, 2014
1 parent 3290700 commit 36456ac
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 118 deletions.
12 changes: 12 additions & 0 deletions ch11/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,15 @@ What would happen if a line in that file has a key, one space, and then the end
we added a file that name "word_transformation_bad.txt" to folder `data`. the file only has a key, one space.

the program of 11.33 don't influenced by that.

## Exercise 11.37:
>What are the advantages of an unordered container as compared to the ordered version of that container? What are the advantages of the ordered version?
- the advantages of an unordered container:
- useful when we have a key type for which there is no obvious ordering relationship among the elements
- useful for applications in which the cost of maintaining the elements in order is prohibitive
- the advantages of the ordered version:
- Iterators for the ordered containers access elements in order by key
- we can directly define an ordered container that uses a our own class types for its key type.

## [Exercise 11.38](ex11_38.cpp)
118 changes: 0 additions & 118 deletions ch11/ex11_37_38.cpp

This file was deleted.

50 changes: 50 additions & 0 deletions ch11/ex11_38.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//
// ex11_38.cpp
// Exercise 11.38
//
// Created by pezy on 12/18/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p. 440) programs to use an unordered_map.

#include <unordered_map>
#include <set>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

using std::string;

void wordCounting()
{
std::unordered_map<string, size_t> word_count;
for (string word; std::cin >> word; ++word_count[word]);
for (const auto &w : word_count)
std::cout << w.first << " occurs " << w.second << (w.second > 1 ? "times" : "time") << std::endl;
}

void wordTransformation()
{
std::ifstream ifs_map("../data/word_transformation.txt"), ifs_content("../data/given_to_transform.txt");
if (!ifs_map || !ifs_content) {
std::cerr << "can't find the documents." << std::endl;
return;
}

std::unordered_map<string, string> trans_map;
for (string key, value; ifs_map >> key && getline(ifs_map, value); )
if (value.size() > 1) trans_map[key] = value.substr(1).substr(0, value.find_last_not_of(' '));

for (string text, word; getline(ifs_content, text); std::cout << std::endl)
for (std::istringstream iss(text); iss >> word; ) {
auto map_it = trans_map.find(word);
std::cout << (map_it == trans_map.cend() ? word : map_it->second) << " ";
}
}

int main()
{
//wordCounting();
wordTransformation();
}

0 comments on commit 36456ac

Please sign in to comment.