473,841 Members | 1,843 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function to output words in a vector and the occurrence.

Hi,

I have an exercise that requests the following:

Write a function that reads words from an input stream and stores them
in a vector.
Use that function both to write programs that count the number of
words in the input,
and to count how many times each word occurred.

The below code works fine, but would like some advice on the
occurrence count.

I have commented out the part that concerns me.

#include <iostream>
#include <vector>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::string;
using std::vector;

istream& read(istream& in, vector<string>& words)
{
if (in)
{
words.clear();
string temp;
while (in >temp)
words.push_back (temp);

in.clear();
}
return in;
}

int main()
{
cout << "Enter a list of words:" << endl;

vector<stringwo rds;
read(cin, words);

vector<string>: :size_type vecSize = words.size();

cout << "You entered " << vecSize << " words." << endl;

for (vector<string> ::size_type i = 0; i < vecSize; i++)
{
int wordCount = 0;
for (vector<string> ::size_type j = 0; j < vecSize; j++)
{
if (words[i] == words[j])
{
wordCount += 1;
//if (wordCount 1)
//{
// words.erase(wor ds.begin() + j);
// vecSize = words.size();
//}
}
}
cout << "The word: " << words[i] << " occured " << wordCount
<< " times." << endl;
}

return 0;
}

With that portion of code commented, let's say I have an input with
the words:

"This that then that"

My output will appear as:

You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.
The word: that occured 2 times.

With the code uncommented, the output appears as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.

Which is what I am after, but is commented code a poor method to
achieve this effect?

I have done a search and made a note of some responses using a
container of <string, int>, but the book I am following has not
covered this aspect.
Also I am aware of the use of size_t over ::size_type, but the book
has it's own method and am using that for the time being. It has also
not covered the use of ::iterator just yet.

Any advice is appreciated.

Apr 19 '07 #1
6 3953
"Xernoth" <Jo********@goo glemail.comwrot e in message
news:11******** **************@ e65g2000hsc.goo glegroups.com.. .
Hi,

I have an exercise that requests the following:

Write a function that reads words from an input stream and stores them
in a vector.
Use that function both to write programs that count the number of
words in the input,
and to count how many times each word occurred.

The below code works fine, but would like some advice on the
occurrence count.

I have commented out the part that concerns me.

#include <iostream>
#include <vector>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::string;
using std::vector;

istream& read(istream& in, vector<string>& words)
{
if (in)
{
words.clear();
string temp;
while (in >temp)
words.push_back (temp);

in.clear();
}
return in;
}

int main()
{
cout << "Enter a list of words:" << endl;

vector<stringwo rds;
read(cin, words);

vector<string>: :size_type vecSize = words.size();

cout << "You entered " << vecSize << " words." << endl;

for (vector<string> ::size_type i = 0; i < vecSize; i++)
{
int wordCount = 0;
for (vector<string> ::size_type j = 0; j < vecSize; j++)
{
if (words[i] == words[j])
{
wordCount += 1;
//if (wordCount 1)
//{
// words.erase(wor ds.begin() + j);
// vecSize = words.size();
//}
}
}
cout << "The word: " << words[i] << " occured " << wordCount
<< " times." << endl;
}

return 0;
}

With that portion of code commented, let's say I have an input with
the words:

"This that then that"

My output will appear as:

You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.
The word: that occured 2 times.

With the code uncommented, the output appears as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.

Which is what I am after, but is commented code a poor method to
achieve this effect?

I have done a search and made a note of some responses using a
container of <string, int>, but the book I am following has not
covered this aspect.
Also I am aware of the use of size_t over ::size_type, but the book
has it's own method and am using that for the time being. It has also
not covered the use of ::iterator just yet.

Any advice is appreciated.
Well, you didn't specify what tools you were allowed to use. If you are
allowed to use std::map it becomes extremely easy. Consider.

std::map<std::s tring, intWordCount;
// for loop
WordCount[words[i]]++;

This one line of code does a whole bunch of things. You can add an entry to
a map by specifing a key that doesn't already exist in []. Then it would
increment it. A map has it's data part (.second) default constructued, for
an int it means it would be 0.

So... if WordCount[words[i]] doesn't exist, it adds it to the map, makes the
int 0, then increments it becuase of the ++ post increment.
If it already exists, it simply increments it.

When you are done iteratring through your words, you have a map keyed by the
word where the value is the number of times it appeared.

Iterate through the map when you are done to dispaly the values.
Apr 19 '07 #2
On Apr 20, 12:53 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
Well, you didn't specify what tools you were allowed to use. If you are
allowed to use std::map it becomes extremely easy. Consider.

std::map<std::s tring, intWordCount;
// for loop
WordCount[words[i]]++;
Yes, this is what I read on another post as a solution, however the
book has not yet covered ::map. For the record, it's the Accelerated C+
+ book. Chapter 4, exercise 4-5.

Apr 20 '07 #3
On 20 Apr, 01:32, Xernoth <JonH.Pe...@goo glemail.comwrot e:
Hi,

I have an exercise that requests the following:

Write a function that reads words from an input stream and stores them
in a vector.
Use that function both to write programs that count the number of
words in the input,
and to count how many times each word occurred.

The below code works fine, but would like some advice on the
occurrence count.

I have commented out the part that concerns me.

#include <iostream>
#include <vector>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::string;
using std::vector;

istream& read(istream& in, vector<string>& words)
{
if (in)
{
words.clear();
string temp;
while (in >temp)
words.push_back (temp);

in.clear();
}
return in;

}

int main()
{
cout << "Enter a list of words:" << endl;

vector<stringwo rds;
read(cin, words);

vector<string>: :size_type vecSize = words.size();

cout << "You entered " << vecSize << " words." << endl;

for (vector<string> ::size_type i = 0; i < vecSize; i++)
{
int wordCount = 0;
for (vector<string> ::size_type j = 0; j < vecSize; j++)
{
if (words[i] == words[j])
{
wordCount += 1;
//if (wordCount 1)
//{
// words.erase(wor ds.begin() + j);
// vecSize = words.size();
//}
}
}
cout << "The word: " << words[i] << " occured " << wordCount
<< " times." << endl;
}

return 0;

}

With that portion of code commented, let's say I have an input with
the words:

"This that then that"

My output will appear as:

You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.
The word: that occured 2 times.

With the code uncommented, the output appears as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.

Which is what I am after, but is commented code a poor method to
achieve this effect?
I'm not sure how much better it it but it would reduce the code to a
single loop if you first sorted the vector (using std::sort()) and
then went through the vector and took notice of when the word changed,
something like this (totally untested):

cout << "You entered " << vecSize << " words." << endl;

sort(words.begi n(), words.end())

string currentWord = words[0];
int wordCount = 0;
for (vector<string> ::size_type i = 0; i < vecSize; i++)
{
if (words[i] == currentWord)
++wordCount;
else
{
cout << "The word: " << currentWord << " occured " << wordCount <<
" times\n";
wordCount = 1;
currentWord = words[i];
}
}

--
Erik Wikström

Apr 20 '07 #4
I'm not sure how much better it it but it would reduce the code to a
single loop if you first sorted the vector (using std::sort()) and
then went through the vector and took notice of when the word changed,
something like this (totally untested):
You are not the only one who thought that :)) when I was reading that
book I tried out sth like this:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
int main(){

std::string x;
std::vector<std ::stringinput;
std::vector<std ::stringsorted_ input;
std::vector<std ::stringwords;
std::vector<int counts;
std::vector<std ::string>::size _type vec_sz;
int count=1;
while(std::cin >x)
input.push_back (x);

sort(input.begi n(),input.end() );

std::string test=input[0];

vec_sz=input.si ze();

for(unsigned i=0;i!=vec_sz;+ +i)
std::cout << input[i] << std::endl;
for(unsigned k=1;k!=vec_sz;+ +k){

if(input[k]==test){
++count;
if(k==vec_sz-1){
words.push_back (test);
counts.push_bac k(count);
}
}
else{
words.push_back (test);
counts.push_bac k(count);
test=input[k];
count=1;
if(k==vec_sz-1){
words.push_back (test);
counts.push_bac k(count);
}
}
}
vec_sz=words.si ze();
std::cout << "WORDS" <<"\t"<<"OCCURE NCE#"<<std::end l;
for(unsigned i=0;i!=vec_sz;+ +i)
std::cout << words[i]<<"\t" << counts[i]<< std::endl;

return 0;

}
Hope it helps, feel free to experiment on the code... not the elegant
way to accomplish the task but a humble different approach.

Greetings,

Apr 20 '07 #5
On Apr 20, 7:18 am, Erik Wikström <eri...@student .chalmers.sewro te:
I'm not sure how much better it it but it would reduce the code to a
single loop if you first sorted the vector (using std::sort()) and
then went through the vector and took notice of when the word changed,
something like this (totally untested):
utab wrote:
You are not the only one who thought that :)) when I was reading that
book I tried out sth like this:
Thanks to both of you. That seems like a good approach, and more to
what the book is looking for, since it does not cover the use of any
extra functions for vectors.
I'll give that a try, but looking over the code, will seem to do just
what I'm after.

Apr 20 '07 #6
In article <11************ **********@b58g 2000hsg.googleg roups.com>,
er****@student. chalmers.se says...

[ ... ]
With the code uncommented, the output appears as:
You entered 4 words.
The word: this occured 1 times.
The word: that occured 2 times.
The word: then occured 1 times.

Which is what I am after, but is commented code a poor method to
achieve this effect?
I'd do this a bit differently, something like this:

// Warning: this code has received only minimal testing.
//
typedef std::pair<std:: string, intword_count;

namespace std {
// I believe putting this in ::std is officially cheating, but...
std::ostream &operator<<(std ::ostream &os, word_count const &p) {
os << "The word: " << p.first
<< " occurred " << p.second << " times.";
return os;
}
}

void count(std::istr eam &in, std::ostream &out) {
std::map<std::s tring, intword_counts;

std::string temp;

while (in >temp)
++word_counts[temp];

std::copy(word_ counts.begin(), word_counts.end (),
std::ostream_it erator<word_cou nt>(out, "\n"));
}

Another possibility would be to collect the words in a multiset, and
then use std::equal_rang e and std::distance to produce the output.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Apr 21 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1675
by: Thomas Köllmann | last post by:
Hi, everybody! I'm teaching myself Python, and I have no experience in programming apart from some years of shell scripting. So, please bear with me. These two funktions are part of an administrative script I've set myself as a first lesson, and, as you will see, they're practically the same, except for one variable. So I'd like to weld them together -- but I can't find out how to.
10
1789
by: Huibuh | last post by:
The following code is a function called from the main. Sence is to initialize a vector of the dimension of "a". "b" is the according value (all the same in a vector). The problem is that the initialization is done the right way (controled by the output) but the returned vector is empty - meaning the pointer is showing zero.
6
4118
by: Mike Darrett | last post by:
Hello, First off, I'm a C++ newbie, so please turn your flame guns off. ;) I'm wondering if this is the correct way to have a function return a vector: vector<int> GetVecData() { vector<int> ret;
6
1504
by: utab | last post by:
Dear all, I am trying to count the occurence of words in an input stream I can keep my words in a vector<string> as below; #include <iostream> #include <cmath> #include <vector> #include <iomanip> #include <string>
3
1612
by: utab | last post by:
Dear, The thing I would like to do is to write a function(count) that counts the occurence of words in my input. If the vector is like "st1" "st1" "st2" "st2" "st2"
7
9350
by: abraxas | last post by:
Ok maybe someone here can help me. I have been learning c++ and have been toying with some basic programming and have run into something that I would have assumed would have been fairly easy. I am wanting to input a list of words into the program and I thought you would use and array to do that, but I am not having any luck finding info on storing an actual list of words. I have set it up so that it prompts you for the number of words. ...
10
3928
by: Johny | last post by:
I need to find all the same words in a text . What would be the best idea to do that? I used string.find but it does not work properly for the words. Let suppose I want to find a number 324 in the text '45 324 45324' there is only one occurrence of 324 word but string.find() finds 2 occurrences ( in 45324 too)
11
1786
by: Daniel T. | last post by:
The function below does exactly what I want it to (there is a main to test it as well.) However, I'm curious about ideas of making it better. Anyone interested in critiquing it? void formatText( const string& in, int charsPerLine, int lines, vector< string >& out ) { out.resize( 1 ); out = ""; int prev = 0;
8
1850
TimNick90
by: TimNick90 | last post by:
I am making a hangman program for school that uses a function for the player to input their guess and a seperate function to test whether or not their guessed letter is in the word. The program worked fine without the function to test the players guess but when i copied the code from the main program and turned it into the function i had to change most of the variables to global. All but one is working, my "soFar" string is supposed to change...
0
9865
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10609
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10303
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9446
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7025
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5694
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3140
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.