0

I trying to make a C++ code that delete occurrences of an element if it occurs more than "n" times, when I debug the code, apears a window with the message: "Debug Assertion Failed!"

Here is the code:

#include<iostream>
#include<vector>

std::vector <int> deleteNth(std::vector<int> arr, int n) {
    
    int asi = sizeof(arr) / sizeof(arr[0]);
    int cont = 0;
    int i;
    int j;
    int k;

    for (i = 0; i < asi; ++i)
        for (j = i + 1; j < asi;)
        {
            if (arr[i] == arr[j])
            {
                ++cont;
                if (cont == n) {

                    for (k = j; k < asi - 1; ++k)
                        arr[k] = arr[k + 1];
                    --asi;
                }

            }
            else
                ++j;
        }

    std::vector<int> newarr;
    newarr.resize(asi);

    return newarr;
}

int main() {
    int i;
    std::vector<int> arr_final = deleteNth({ 20,37,20,21 }, 1);
    int arrsize_ext = sizeof(arr_final ) / sizeof(arr_final[0]);
    
    for (i = 0; i < arrsize_ext; ++i)
        cout << arr_final[i] << " ";
}
  • 2
    `sizeof(arr) / sizeof(arr[0])` only works on plain arrays, use `arr.size()` for vectors. There's also `std::size(arr)` which works for *both* arrays and vectors (that's what you should use for arrays). – HolyBlackCat May 13 '22 at 19:27
  • Take a look at [How do sizeof(arr) / sizeof(arr\[0\]) work?](https://stackoverflow.com/questions/33523585/) It's not working for you because the size of a `std::vector` is typically the size of 3 pointers. It's calculated at compile time and does not check the contents of the vector. – Drew Dormann May 13 '22 at 19:31
  • 1
    This doesn't address the question, but `std::vector newarr; newarr.resize(asi); return newarr;` will return a vector of `int` holding the same number of values as the original vector (assuming the code that computes `asi` gets fixed) with all the values in the vector set to 0. That's probably not what was intended. – Pete Becker May 13 '22 at 19:32

0 Answers0