patterncppMinor
Exercise from Accelerated C++
Viewed 0 times
fromexerciseaccelerated
Problem
I am working through the exercises in the book Accelerated C++. I wanted to get some feedback on proper use of the Standard Library, correctness, overall style, portability, etc.
/*******************************************************************************
Accelerated C++ Chapter 3
Write a program to count how many times each distinct word appears in its input
*******************************************************************************/
#include
#include
#include
int main()
{
std::cout ::size_type vector_sz;
std::vector words;
std::string word;
while (std::cin >> word)
{
words.push_back(word);
}
vector_sz size = words.size();
if(size == 0)
{
std::cout frequency;
std::vector unique_words;
int count = 0;
bool isUnique;
unique_words.push_back(words[0]);
for(unsigned i = 0; i < words.size(); ++i)
{
isUnique = true;
for(unsigned j = 0; j < unique_words.size(); ++j)
{
if(words[i] == unique_words[j])
{
isUnique = false;
}
}
if(isUnique)
{
unique_words.push_back(words[i]);
}
}
for(unsigned i = 0; i < unique_words.size(); ++i)
{
for(unsigned j = 0; j < words.size(); ++j)
{
if(unique_words[i] == words[j])
{
count += 1;
}
}
frequency.push_back(count);
count = 0;
}
for(unsigned i = 0; i < unique_words.size(); ++i)
{
std::cout << unique_words[i] << " " << frequency[i] << std::endl;
}
return 0;
}Solution
You could cut your code in half if you used a map:
Couple other notes from the code you have:
typedef std::map Map;
Map tMap;
while(std::cin >> word)
{
// When accessing a map with `[]` If the value does not exist
// it is created and initialized to zero.
//
// The plus plus then increments the stored value
tMap[word]++;
}
// Iterate through map and print frequencyCouple other notes from the code you have:
- After
unique_words.push_back(words[0]);you can start theiloop at index 1 instead of 0.
- When checking for uniqueness in the first pair of loops, once you determine uniqueness to be false you can stop looping for that word: `while(j
Code Snippets
typedef std::map<std::string, unsigned int> Map;
Map tMap;
while(std::cin >> word)
{
// When accessing a map with `[]` If the value does not exist
// it is created and initialized to zero.
//
// The plus plus then increments the stored value
tMap[word]++;
}
// Iterate through map and print frequencyContext
StackExchange Code Review Q#12342, answer score: 6
Revisions (0)
No revisions yet.