没有比较正确的向量元素
Not comparing the correct vector elements
我正在接收一个文本文件并将单词放入向量中。如果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';
}
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C