Daniel Poh
Daniel Poh

Reputation: 129

Modify part of an array

I want to modify elements in an array from index A to B.

Example: I have an array [0, 0, 0, 0, 0]. I want to increment elements between index 1 to 2 by 1 such that the array will be [0, 1, 1, 0, 0] at the end of the operation. Is there any better way to do this rather than looping through the array and modifying them one by one?

I am going to apply this to a big array so it would be best if there is a way to do this without the use of loops.

Sample:

#include <bits/stdc++.h>
using namespace std;

int main() {
    // initialisation
    int arr[5];
    int first_indx = 1, last_indx = 2;
    fill(arr, arr + 5, 0);
    cout << "Initial: \n";
    for (int a : arr) {
        cout << a << ", ";
    }
    cout << "\n";
    // operation to modify array
    for (int b = 0; b < 5; b++) {
        if (first_indx <= b && b <= last_indx) {
            arr[b]++;
        }
    }
    // output
    cout << "After modification: \n";
    for (int c : arr) {
        cout << c << ", ";
    }
}

Output:

Initial:
0, 0, 0, 0, 0,
After modification:
0, 1, 1, 0, 0,

Upvotes: 0

Views: 160

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

You can use the loop and as others pointed out you need not iterate the whole range just to skip elements out of the desired range. A different way to achieve the same is already present in your code:

fill(arr, arr + 5, 0);

This fills elements from the first (arr decays to a pointer to the first element here) till the last (arr + 5) with 0. To assign a differnt value in a different range you can use the same algorithm:

int start = 1;
int end = 3;
std::fill(arr + start, arr + end, 1);

Make sure the range is valid (ie not out of bounds of the array). Note that I used a half open range, ie start is included, end is not included, because it is common convention to do so.

Upvotes: 0

Marek R
Marek R

Reputation: 37597

Why you iterating over whole thing?

    for (int b = first_indx ; b <= last_indx; b++) {
        arr[b]++;
    }

Note:
I've got feeling you are solving some online task which is more challenging then you think (there are many ranges which do this modification). Your brutal force solution will not score maximum result, even when you applied fix from answers.

Upvotes: 3

MikeCAT
MikeCAT

Reputation: 75062

It is better to loop only within the range to modify than looping among the whole array.

    // operation to modify array
    for (int b = first_indx; b <= last_indx; b++) {
        arr[b]++;
    }

Upvotes: 4

Related Questions