C++ 不比较正确的向量元素
我把一个文本文件放到一个向量中。如果向量已经包含单词,它将增加occurance memeber。如果是新词,我们把它推到向量上。当我调试这个时,一切看起来都是正确的,但是向量中填充了每一个单词,因为“I”似乎落后一个索引 但是,如果我用I=1初始化,向量将超出范围。有什么帮助吗C++ 不比较正确的向量元素,c++,input,vector,C++,Input,Vector,我把一个文本文件放到一个向量中。如果向量已经包含单词,它将增加occurance memeber。如果是新词,我们把它推到向量上。当我调试这个时,一切看起来都是正确的,但是向量中填充了每一个单词,因为“I”似乎落后一个索引 但是,如果我用I=1初始化,向量将超出范围。有什么帮助吗 vector<wordFreq> words; //already have 1 in vector, i initialized at 0. while(!myfile.eof()) {
vector<wordFreq> words;
//already have 1 in vector, i initialized at 0.
while(!myfile.eof())
{
myfile >> tempWord; //takes word into variable
if (words[i].wordName == tempWord) //if it is found
{
//words[i].occurances++; //increment occurance member
}
else
{
//create new object
wordFreq tempElement;
tempElement.occurances = 1;
tempElement.wordName = tempWord;
words.push_back (tempElement); //push onto vector
}
i++;
}
向量词;
//向量中已经有1,我初始化为0。
而(!myfile.eof())
{
myfile>>tempWord;//将word放入变量
if(words[i].wordName==tempWord)//如果找到它
{
//words[i].发生+++;//递增发生成员
}
其他的
{
//创建新对象
wordFreq元素;
tempElement.occurances=1;
tempElement.wordName=tempWord;
words.push_back(tempElement);//推到向量上
}
i++;
}
将(!myfile.eof())myfile>>tempWord更改为
while ( myfile >> tempWord )
否则,您将得到一个额外的循环迭代和一个垃圾字
不管怎么说,听起来好像你想在每个单词的整个向量中循环找到它,例如:
int i;
for (i = 0; i < words.size(); ++i)
if ( words[i] == tempWord )
{
++words[i].occurances;
break;
}
if ( i == words.size() ) // not found
{
// create new object...
}
inti;
对于(i=0;i
虽然这可以很好地工作,但是有一些标准算法可以为您完成这项工作,特别是find
函数。检查find
的文档,看看是否可以将for
循环替换为find
最后,如果使用
std::map
而不是向量,则可以用++my_map[tempWord]替换整个代码块代码>如果您只想计算单词的出现次数,也许地图可以帮助您:
map<string, int> m;
string tempWord;
while (myfile >> tempWord) ++m[tempWord];
// print out
for (map<string, int>::const_iterator p = m.begin(); p != m.end(); ++p) {
cout << p->first << '\t' << p->second << '\n';
}
map-m;
字符串临时字;
而(myfile>>tempWord)++m[tempWord];
//打印出来
for(map::const_迭代器p=m.begin();p!=m.end();++p){
首先请标记您的语言。首先,这是:while(!myfile.eof())
。如果您可以使用or而不仅仅是向量,那么这很快就会变得微不足道。