没有比较正确的向量元素

Not comparing the correct vector elements

本文关键字:向量 元素 比较      更新时间:2023-10-16

我正在接收一个文本文件并将单词放入向量中。如果vector对象已经包含该单词,则对其出现成员进行加1操作。如果是生词,我们把它推到向量上。当我调试它时,一切似乎都是正确的,但是向量被每个单词填充,occurrence = 1,因为"I"似乎落后一个索引。

如果我初始化I =1,向量将超出范围。任何帮助吗?

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++;
}

while(!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...
}

虽然这可以很好地工作,但有一些标准算法可以为您完成这项工作,特别是find函数。检查find的文档,看看是否可以用find替换for循环。

最后,如果您使用std::map而不是矢量,则可以将整个代码块替换为++my_map[tempWord].occurances;

如果你只想计算单词的出现次数,也许地图可以帮助你:

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';
}