473,799 Members | 3,740 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

argg, noob array question

I have an array with 50 elements in it, and a huge document with like
35,000 words on it. What I want to do is count the number of times each
element has appeared in the document. This is what I have, what am I
doing wrong?

int search(ifstream & inFile, string keywords[], int SIZE)
{
int counter = 0, k;
string target;
inFile >> target;
for(k = 0; k < SIZE; k++)
{
if(target == keywords[k])
{
counter++;
}
inFile >> target;
}

return counter;
}

Apr 13 '06 #1
4 1897
On Wed, 12 Apr 2006 21:56:16 -0700, foker wrote:
I have an array with 50 elements in it, and a huge document with like
35,000 words on it. What I want to do is count the number of times each
element has appeared in the document. This is what I have, what am I doing
wrong?

int search(ifstream & inFile, string keywords[], int SIZE) {
int counter = 0, k;
string target;
inFile >> target;
for(k = 0; k < SIZE; k++)
{
if(target == keywords[k])
{
counter++;
}
inFile >> target;
}
}
return counter;
}
}


1) use an stl container like a map<string,int> to hold your list of words
being searched for and number of times each word in found, and
2) dont pass an array of strings by value; instead pass map<string,int> &
keywords to your search() function

learn to use stl containers and iterators and your life will be much
easier
Apr 13 '06 #2
"foker" <br************ @gmail.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
:I have an array with 50 elements in it, and a huge document with like
: 35,000 words on it. What I want to do is count the number of times each
: element has appeared in the document. This is what I have, what am I
: doing wrong?
:
: int search(ifstream & inFile, string keywords[], int SIZE)
: {
: int counter = 0, k;
NB: it is best to only declare your variables at first
use ... k has nothing to do up here.

: string target;
: inFile >> target;
: for(k = 0; k < SIZE; k++)
: {
: if(target == keywords[k])
: {
: counter++;
: }
: inFile >> target;
: }
:
: return counter;
: }

You seem to have incorrectly merged two loops into one:
you want to read each word in the file, and compare it
to each word in the array. 2xeach => 2 loops:
while( inFile >> target )
for( int k = 0 ; k<Size ; ++k )
You should be able to easily fill up the rest.
Note also that the inner loop could be replaced by a call
to a standard library function (#include <algorithm>):
counter += std::count( keywords, keywords+SIZE, target );
hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Apr 13 '06 #3
I havent learned STL containers or maps yet. Still having a few
problems.

while(inFile >> target)
for(int k = 0; k < SIZE; k++)
{
if(keywords[k] == target)
{
temp = k;
num_of_times_re ad[temp] += counter++;
}
}
for(int index = 0; index < SIZE; index++)
cout << num_of_times_re ad[temp];
return 0;
}

What I want it to do is read in every word from the document and test
it against every element in keywords array, if it matches i want the
index # from keywords assigned to a temp variable, then i want
num_of_times_co unted[temp] to hold the number of times it was counted
each time it hits that keyword in the document. To me it makes complete
sense but it doesn't work haha, what am I doing wrong here?

say, target matches index #6 in keywords array. I want temp = 6, so
num_of_times_re ad[6] = count++. can I do this?

btw, counter += std::count( keywords, keywords+SIZE, target ); gave a
ton of errors.

Apr 13 '06 #4
"foker" <br************ @gmail.com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
:I havent learned STL containers or maps yet. Still having a few
: problems.
:
: while(inFile >> target)
: for(int k = 0; k < SIZE; k++)
: {
: if(keywords[k] == target)
: {
: temp = k;
: num_of_times_re ad[temp] += counter++;
You probably want to increment this only once,
not by the total previous count of all hits.
Therefore:
num_of_times_re ad[temp] += 1; // or just ++notr[k];
: }
: }
: for(int index = 0; index < SIZE; index++)
: cout << num_of_times_re ad[temp];

Did I not warn you, in my previous post, that you should
not declare variables at the beginning of your function,
but as late as possible (and in the innermost scope) ?

Here you are misusing the variable 'temp' within the second
loop, instead of index.

: return 0;
: }
:
: What I want it to do is read in every word from the document and test
: it against every element in keywords array, if it matches i want the
: index # from keywords assigned to a temp variable, then i want
: num_of_times_co unted[temp] to hold the number of times it was counted
: each time it hits that keyword in the document. To me it makes complete
: sense but it doesn't work haha, what am I doing wrong here?
:
: say, target matches index #6 in keywords array. I want temp = 6, so
: num_of_times_re ad[6] = count++. can I do this?

Yes. Actually "noone"'s reply hinted towards something closer to what
you are looking for.

Here's a quick example thrown together:

#include <fstream>
#include <string>
#include <map>
using namespace std;

void printCounts(ifs tream& inFile, string keywords[], int size)
{
typedef map<string,int> Cnts; // sorted keyword -> its count
Cnts cnts;
// fill up a map for faster search than with array
for( int i = 0 ; i != size ; ++i )
cnts[keywords[i]] = 0;

// read file, for each word check if it is within our map
string target;
while( inFile>>target ) {
Cnts::iterator const pos = cnts.find( target );
if( pos != cnts.end() ) { // actually found
++pos->second; // increment the count
}
}

// now print keyword counts in original order
for( int i = 0 ; i != size ; ++i )
cout<< keywords[i] << " -> " << cnts[keywords[i]] <<endl;
}

Not tested, but will hopefully at least compile.
The best way to write such a function depends on what exactly
you want to do...

: btw, counter += std::count( keywords, keywords+SIZE, target );
: gave a ton of errors.
Well, there are many reasons for which this might have happened.
Good luck,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Apr 13 '06 #5

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

Similar topics

1
1997
by: NewsHound | last post by:
I've been playing around with Perl for a while, but I'm still something of a beginner. I was wondering what happens in the following case. Take a "foreach" loop iterating through the sorted keys of a hash: foreach $key (sort keys %hash) { # do stuff here } Does the "sort" function re-sort the keys before each iteration of the "foreach" loop? I was wondering if it is possible to insert additional
2
1718
by: anti-guru | last post by:
This is killing me. How can I make a static array of two strings in my class? Nothing I've tried works. Here is what I currently have, which also doesn't work, but gives the least amount of compiler errors: in my header file: private: static char *stringTable;
8
2145
by: Ivan Shevanski | last post by:
Alright heres another noob question for everyone. Alright, say I have a menu like this. print "1. . .Start" print "2. . .End" choice1 = raw_input("> ") and then I had this to determine what option.
3
1611
by: newatthis | last post by:
hi am new at c++ and am trying my best to learn but am having a little trouble understand one aspect that has been repeated in many text books all with very vague explanations. i am hoping someone can clear some of this up for me. my question is in regards to arrays and vectors. i understand that c++ counts from 0+ and not the natural numbers 1+ so an array of test(23) would be in the range 0-22?
7
1928
by: DJP | last post by:
Hi, I had sort of a noob question on memory allocation for strings. char *str1 = "Hello World!"; char str2 = "Hello World!"; In the above bit are both str1 & str2 stack allocated or heap allocated or otherwise? Also, unless explicitly malloc'ing a string buffer are we not required to free it? Or are there other circumstances in which we
3
1243
by: ernie.bornheimer | last post by:
Okay, I know how to: - construct a SQL query and get a result set - loop through the result set and echo the fields I need But what I really need to do is get a value from a field and put it in a variable, and I can't seem to get it to work, because then the variable just holds "resource id#" So the query I'm using returns only one row, since I'm filering on the primary key, and I can test for one row returned. If one row is returned,...
5
1618
by: Milan Krejci | last post by:
the thing is that descentant branches i dont want to expand do expand. $id variable contains an array of branches i want the program to go through (alcohol's id -beer id etc) function tree_list($parent, $level,$id) { // retrieve all children of $parent $result = mysql_query('SELECT cname,cid FROM kategorie '. 'WHERE parent="'.$parent.'";'); while ($row = mysql_fetch_array($result)) {
8
1261
by: azz131 | last post by:
Hi, i want to access an array of objects inside a method like this using System; using System.Collections.Generic; namespace ObjectArray { class MainClass{ class MyClass
2
1497
by: tavspamnofwd | last post by:
I'm a total noob, and I'm trying to understand this code: var newsi = { name:"newsi", dom:false }; newsi.Client=function(){ //stuff }
0
10485
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10252
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
10027
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
9073
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...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5463
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.