-1

i try to reduce the length of an array after delete element i have try array:

int* arr = new int[5];
    for (int i = 0; i < 5; i++) {
        arr[i] = i;
}

and the function:

void del1(int* arr, int n) {
    int pos = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 3) {
            pos = i;
        }
    }
    for (int i = pos; i < n - 1; i++) {
        arr[i] = arr[i + 1];
    }
    arr[n - 1] = 0;

    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
}

is there a way to reduce the length of the array that sent to the function?

8
  • 2
    What does "reduce the length of the array that sent to the function" mean? Please be specific. Commented Feb 26, 2023 at 15:49
  • Have you ever looked at std::vector? C++'s resizable array? In any case stop using "C" style arrays as you are doing now and have a look at the C++ core guidelines regarding new/delete. New/delete hardly ever need to be used unless you are writing your own datastructures. Commented Feb 26, 2023 at 15:52
  • Do you mean reduce the size of your array that's passed as a parameter to del1 function? Commented Feb 26, 2023 at 15:53
  • by reduce the length i mean at the beginning the length is 5, and after using te function the length will be 4 Commented Feb 26, 2023 at 16:01
  • does this answer your question? [stackoverflow.com/questions/3749660/how-to-resize-array-in-c] Commented Feb 26, 2023 at 16:04

1 Answer 1

0

What you are looking for is expressed like this in C++ : (online demo : https://onlinegdb.com/OiDJg4849)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> values{ 1,2,3,4,5 };

    // remove/erase idiom 
    // https://en.cppreference.com/w/cpp/algorithm/remove
    // the last argument is a lambda expression
    // https://en.cppreference.com/w/cpp/language/lambda

    auto it = std::remove(values.begin(), values.end(), 3);
    values.erase(it, values.end());

    //https://en.cppreference.com/w/cpp/language/range-for
    for (const auto& value : values)
    {
        std::cout << value << "\n";
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.