-
Problem Filling Vector
Hi. I am attempting to fill a vector with characters from a text file. I want to have the vector hold a dual object - a character and an integer count. I'm trying to fill the vector, but can't quite figure out how to do this. Here is an attempt below. Any ideas will be greatly apppreciated. Thanks.
Code:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<vector>
using namespace std;
class Find
{
public:
Find();
void setChar(char chr);
char getChar();
void setCount(int ct);
int getCount();
void countAdd();
friend ostream& operator <<(ostream& of, Find f)
{
of<<"Found "<<f.count<<" of "<<f.ch;
return of;
}
private:
char ch;
int count;
};
int main(int argc, char* argv[])
{
ifstream in (argv[1]);
char cz;
vector <Find> v;
Find f;
while(in.get(cz))
{
for(int i=0; i<v.size(); i++)
{
if(v[i].getChar() == cz)
{
v[i].countAdd();
break;
}
else
{
f.setChar(cz);
f.setCount(1);
v.push_back(f);
}
}
}
for(int i=0; i<v.size(); i++)
{
cout<<v[i]<<endl;
}
return 0;
}
Find::Find() : ch(0), count(0) {}
void Find::setChar(char chr)
{
ch=chr;
}
char Find::getChar()
{
return ch;
}
void Find::setCount(int ct)
{
count=ct;
}
int Find::getCount()
{
return count;
}
void Find::countAdd()
{
count++;
}
-
I think you need to rework your logic slightly. Perhaps something like this.
Code:
int main(int argc, char* argv[])
{
ifstream in (argv[1]);
char cz;
vector <Find> v;
Find f;
while(in.get(cz))
{
bool found = false;
for(int i=0; i<v.size(); i++)
{
if(v[i].getChar() == cz)
{
v[i].countAdd();
found = true;
break;
}
}
if (!found)
{
f.setChar(cz);
f.setCount(1);
v.push_back(f);
}
}
for(int i=0; i<v.size(); i++)
{
cout<<v[i]<<endl;
}
return 0;
}
-
You might want to consider learning about or using the std::map. You wouldn't have to do that for loop to search the vector, the map would find the char (if it was there) for you.