为什么x值在此循环映射中没有增加? c ++

问题描述 投票:1回答:2

此循环的目的是浏览2d向量并计算第一列中的值出现的频率。如果该值显示全部三遍,那么就可以了。如果不是,那么我想从向量中删除它所在的行。 “ it”迭代器将值存储为(值,频率)。

尽管我目前无法弄清楚如何删除该行,但是我一直试图在第二个for循环中使用一个计数器“ x”,以便它可以跟踪它在哪一行,但是当我通过调试器运行x不会递增。最终发生的是向量删除了第一行,而不是使if语句为true的行。

为什么“ x”不递增?我可以使用其他方法来跟踪循环当前在哪一行吗?

“ data”是2d向量。

        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
2个回答
0
投票

您在每个循环中将x重置为0。在循环外对其进行初始化,它应该可以工作。

int x = 0;

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++;
        }
© www.soinside.com 2019 - 2024. All rights reserved.