Parent directory
Makefile
words1.cpp
words2.cpp
CC = g++
CXX = g++
CFLAGS = -g -Wall
CXXFLAGS = -g -Wall -std=c++20
executables = words1 words2
.PHONY: default
default: $(executables)
words1: words1.o
words2: words2.o
.PHONY: clean
clean:
rm -f *~ a.out core *.o $(executables)
.PHONY: all
all: clean default#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// 1. std::map
map<string,int> m;
// 5. std::unordered_map
// unordered_map<string,int> m;
for (string s; cin >> s; ) {
++m[s];
}
for (auto i = m.begin(); i != m.end(); ++i) {
cout << setw(20) << (*i).first << '|';
cout << i->second << '\n';
}
// 2. Range-based for loop
// for (auto& e : m) {
// cout << setw(20) << e.first << '|' << e.second << '\n';
// }
// 3. Structured binding (C++17)
// for (auto& [s, n] : m) {
// cout << setw(20) << s << '|' << n << '\n';
// }
// 4. Finding an element
// auto it = m.find( "#include"s );
// if (it != m.end()) {
// auto& [s, n] = *it;
// cout << '\n' << s << " appears " << n << " times." << '\n';
// }
}#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Build a map of words to their frequencies
unordered_map<string,int> word_to_freq;
for (string s; cin >> s; ) {
++word_to_freq[s];
}
// Build a reverse map of frequencies to words
multimap<int,string> freq_to_words;
// unordered_multimap<int,string> freq_to_words;
for (const auto& [word, freq] : word_to_freq) {
freq_to_words.insert( {freq, word} );
}
// Output the reverse map
for (const auto& [freq, word] : freq_to_words) {
cout << setw(4) << freq << '|' << word << '\n';
}
// Find out how many words occur three times
auto [b, e] = freq_to_words.equal_range(3);
if (b != e) {
auto& freq = b->first;
auto num_words = distance(b, e);
cout << '\n' << num_words << " words occur " << freq << " times.\n";
}
}