DarknessPlusPlus
DarknessPlusPlus

Reputation: 563

Is there a better way of looping through each element in an array without using an indexed for loop?

I have a triangle class consisting of a triangle's sides perimeter and many helper functions.

I have created a function that will populate an array of instances of triangle. Let us say I will create 3 objects so the triangles parameter will be set to 3.

void populate_triangle(triangle in_array[], int triangles) {
    for (int i = 0; i < triangles; i++) {
        in_array[i].input_random_sides();
        in_array[i].get_perimeter();
    }
}

I have also created a print function that will output all the information about said 3 objects, i.e. the three sides and perimeter.

void print_triangle(trianglein_array[], int triangles) {
    for (int i = 0; i < triangles; i++) {
        cout << "Triangle N: " << i << endl;
        in_array[i].print_information();
    }
}

I later call them in my main using

populate_triangle(in_array, 3);
print_triangle(in_array, 3);

I feel like this way is very inefficient and ugly.

Is there a better way to go through the filled-in array, other than the for (int i = 0; i < triangles; i++) loop? I know I can fuse this into one function, but I want to know how to do it with two.

Upvotes: 1

Views: 380

Answers (1)

Josh Hardman
Josh Hardman

Reputation: 721

As mentioned in the comments, you can use a std::vector.

std::vector keeps track of its own length so when you write your methods, there's no need to include the length as an extra argument, it's automatically deduced in the range for loop.

With a std::vector your method might look something like this:

void populate_triangle(std::vector<Triangle> triangles) {
    for (auto triangle : triangles) {
        triangle.input_random_sides();
        triangle.get_perimeter();
    }
}

std::vector's data array is guaranteed to be stored in contiguous memory.

Upvotes: 2

Related Questions