为什么这个 x 值在这个循环映射中没有增加?C++



此循环的目的是查看二维向量,并计算第一列中出现值的频率。如果该值同时显示三次,则可以继续。如果没有,那么我想从向量中删除它所在的行。"it"迭代器将值存储为(value,frequency(。

不过,我现在不知道如何删除该行,我一直试图在第二个for循环中使用计数器"x",这样它就可以跟踪它所在的行,但当我通过调试器运行它时,x不会递增。最终发生的情况是,向量删除第一行,而不是使if语句为true的行。

为什么"x"不递增?有没有其他方法可以用来跟踪循环当前所在的行?

"data"是二维矢量。

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

每个循环都将x重置回0。在循环外初始化它,它应该可以工作。

int x = 0;

您必须在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++;
}

最新更新