首页 > 解决方案 > 为什么这个 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++;
        }   

标签: c++for-loop

解决方案


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

推荐阅读