c++ - 为什么这个 x 值在这个 map for 循环中没有增加?C++
问题描述
此循环的目的是查看二维向量并计算第一列中的值出现的频率。如果该值全部显示 3 次,那么就可以走了。如果没有,那么我想从向量中删除它所在的行。“it”迭代器将值存储为(值,频率)。
我现在不知道如何删除该行,我一直在尝试在第二个 for 循环中使用计数器“x”,以便它可以跟踪它所在的行,但是当我运行它时通过调试器, x 不会增加。最终发生的是向量删除第一行而不是使 if 语句为真的行。
为什么“x”不增加?我可以使用其他方法来跟踪循环当前所在的行吗?
“数据”是二维向量。
for (int i = 0; i < data.size(); i++) // Process the matrix.
{
occurrences[data[i][0]]++;
}
for (map<string, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end(); ++it)
{
int x = 0;
if ((*it).second < 3) // if the value doesn't show up three times, erase it
{
data.erase(data.begin() + x);
}
cout << setw(3) << (*it).first << " ---> " << (*it).second << endl; // show results
x++;
}
解决方案
您必须在 for 循环之外初始化 x 。如果您在 for 循环中声明它,它将每次都设置为 0。您当前的程序每次都会删除第一个元素,因为 x 在这里始终为零:data.erase(data.begin() + x);
for (int i = 0; i < data.size(); i++) // Process the matrix.
{
occurrences[data[i][0]]++;
}
int x = 0;
for (map<string, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end(); ++it)
{
if ((*it).second < 3) // if the value doesn't show up three times, erase it
{
data.erase(data.begin() + x);
}
cout << setw(3) << (*it).first << " ---> " << (*it).second << endl; // show results
x++;
}
推荐阅读
- typo3 - 在 CommandController 中解析 TYPO3 链接
- google-cloud-platform - 使用 Google Cloud Storage Transfer Service 时保留对文件的公开访问权限
- php - 查看存储在laravel公共/存储中的pdf?
- laravel - 推送器未使用 laravel 发送事件
- python - 如何在python中绘制集群?
- android - DaggerTestAppComponent 未在 Android 测试目录中生成
- c# - 为什么 float.IsFinite 在 Unity 中“未定义”?
- python - 有没有办法从机票网站上提取实时报价?
- html - 列表“图标”中的每个字典都应包含一个非空 UTF8 字符串字段“类型”
- sql - EF Core,FromSqlRaw 与 USE HINT