Apprentice Coder
Apprentice Coder

Reputation: 17

Efficiently setting all array values to zero

I have not written C++ code in a while. I need to set all of the values in this program so far to 0 in an efficient manner.

#include<iostream>
int main(){
    using namespace std;
    double MainTrianglePoint1[2];
    double MainTrianglePoint2[2];
    double MainTrianglePoint3[2];
    std::cout << "Point 1 X:" << MainTrianglePoint1[2] << " Y:" << MainTrianglePoint1[1];
    std::cin.get();
return 0;
}

Is there a loop I can perform on all of the MainTrianglePoint arrays so all of their values are set to 0?

Upvotes: 0

Views: 524

Answers (5)

Artur Pyszczuk
Artur Pyszczuk

Reputation: 1930

In C++11 you can easily do this thing using {}. Consider following code:

#include <iostream>
using namespace std;
int main () {

        double n[10];
        for (int i = 0; i < 10; ++i) {
                cout << n[i] << endl;
        }

        double k[10] {};

        cout << "-" << endl;
        for (int i = 0; i < 10; ++i) {
                cout << k[i] << endl;
        }
        return 0;
}

example

Upvotes: 0

gomons
gomons

Reputation: 1976

I consider to not use loop for that, you cat just fill memory by zeroes:

std::fill(std::begin(MainTrianglePoint1), std::end(MainTrianglePoint1), 0);
std::fill(std::begin(MainTrianglePoint2), std::end(MainTrianglePoint2), 0);
std::fill(std::begin(MainTrianglePoint3), std::end(MainTrianglePoint3), 0);

Upvotes: 1

rpsml
rpsml

Reputation: 1498

With c++03, you can initialize the arrays directly in their declaration:

double MainTrianglePoint1[2] = {0,0};

With c++11 you can drop the = sign:

double MainTrianglePoint1[2] {0,0};

Upvotes: 2

Abhijit
Abhijit

Reputation: 63707

May be you would want to create an unnamed structure and value initialize the members to its default value. Demo

#include<iostream>
using namespace std;
struct  {

    double Point1[2];
    double Point2[2];
    double Point3[2];
} MainTriangle = {};
int main()
{
    std::cout << "Point 1 X:" << MainTriangle.Point1[2] << " Y:" << MainTriangle.Point1[1];
    std::cin.get();

}

Upvotes: 0

Javia1492
Javia1492

Reputation: 892

You can use a for loop to do that.

for(int i = 0; i<2; i++)
{
  MainTrianglePoint1[i] = 0;
  MainTrianglePoint2[i] = 0;
  MainTrianglePoint2[i] = 0;
}

This will loop through each array index up to max size and set the value at the index to 0.

Upvotes: 0

Related Questions