Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 产出不是预期的_C++_List_Loops - Fatal编程技术网

C++ 产出不是预期的

C++ 产出不是预期的,c++,list,loops,C++,List,Loops,这里有一个来自codewars.com的问题 给定一个列表和一个数字N,创建一个新列表,该列表最多包含N次lst的每个数字,而无需重新排序。例如,如果N=2,输入为[1,2,3,1,2,1,2,3],则取[1,2,3,1,2],删除下一个[1,2],因为这将导致1和2在结果中出现3次,然后取3,这将导致[1,2,3,1,2,3] 这是我的代码: std::vector<int> deleteNth(std::vector<int> arr, int n) { int

这里有一个来自codewars.com的问题

给定一个列表和一个数字N,创建一个新列表,该列表最多包含N次lst的每个数字,而无需重新排序。例如,如果N=2,输入为[1,2,3,1,2,1,2,3],则取[1,2,3,1,2],删除下一个[1,2],因为这将导致1和2在结果中出现3次,然后取3,这将导致[1,2,3,1,2,3]

这是我的代码:

std::vector<int> deleteNth(std::vector<int> arr, int n)
{
   int counting = 0;
   int counting2 = 0;
   for (int i : arr)
   {
    for (int j : arr)
    {
     cout << arr.size() << "  " << counting<<"  "<<counting2<<endl;
        if (i == j) 
        {
            ++counting;
            if (counting > n) { arr.erase(arr.begin() + counting2); --counting2; }
        }

        counting2++;
    }
    counting = 0;
    counting2 = 0;
}
return arr;
std::vector deleteNth(std::vector arr,int n)
{
整数计数=0;
整数计数2=0;
用于(int i:arr)
{
对于(int j:arr)
{

我看到这里有两个嵌套的循环。你可以用一个循环实现你想要做的。只需使用频率数组。这里我使用的是
std::map
,因为数字的范围未知。如果范围已知,你可以使用数组或
std::vector
,让代码在O(N)中运行


嗨!看,没人能看一眼就说“啊,是的,你忘了在你的讨价还价函数中填上pfrumpf”,我们需要做的是将其加载到调试器中,逐步执行,查看它从预期路径派生到何处,等等。这会带来额外的开销,特别是因为我们不知道您作为代码作者的知识。如果您可以自己调试代码,这将非常有用。Google
如何调试c++
以及您的c++ompiler查找有关它的信息。或者尝试教程附带的内容。在循环中调用
.erase
是UB。只需创建一个新的向量即可。
#include <iostream>
#include <vector>
#include <map>

std::vector<int> deleteNth(std::vector<int>& arr, int n)
{
    std::map<int, int> freq;
    std::vector<int> result;

    for (int number : arr)
    {
        if (freq[number] >= n)
            continue;

        result.push_back(number);
        freq[number]++;
    }

    return result;
}

int main()
{
    std::vector<int> v{ 1,2,3,1,2,1,2,3 };
    auto result = deleteNth(v, 2);

    for (int i : result)
        std::cout << i << ' ';
}
1 2 3 1 2 3