How could I check if every single element in a vector is zero without looping through them?
Current I have (In semi-MEW form): What this attempts to do is check if all three values of the final vector (its three dimensional... year.) is all zeros, (At the origin), or if it equals any previous vector on all three values.
siteVisited = false; counter = 0;
while (counter < (walkHist.back().size()-1))
{
tdof = 1;
while (tdof <= dimensions)
{
if (walkHist.back().back().at(tdof-1) == 0)
{
siteVisited = true;
}
else
{
siteVisited = false;
break;
}
tdof++;
}
if (siteVisited)
{
goto visited;
}
tdof = 1;
while (tdof <= dimensions)
{
if (walkHist.back().back().at(tdof-1) == walkHist.back().at(counter).at(tdof-1))
{
siteVisited = true;
}
else
{
siteVisited = false;
break;
}
tdof++;
}
if (siteVisited)
{
visited:
...
}
counter++;
}
One way to check if a vector of any length is all zeros, is to convert it to an unsigned value and then compare it to its integer equivalent.
As any() checks if there is any value in the bool array is True or not. So it will return False if all values in the array are 0. Then using not with the returned value, we can confirm if our array contains only 0.
You can use: std::vector<int> v(100); // 100 is the number of elements. // The elements are initialized with zero values.
It depends on what you mean by looping, but this would work:
bool zeros = std::all_of(v.begin(), v.end(), [](int i) { return i==0; });
The reason for the check is important to know. If a zeroed array is important, and is checked regularly, it would be worth sub-classing vector to set a flag whenever a value is added or changed. This would add overhead to all adds, removes and modified, but would make the "is everything zero" test quick.
If your arrays are very often zeroed, it might then be worth writing your own sparse array class (probably based on map). When a non-zero item is added, or an element is changed to non-zero it is entered into the map. When changed to 0 it is removed. Now you know if all the elements are zero because the map will be empty. This will also have the benefit of using much less memory.
However, if the check for a zeroed array is comparatively rare, then any loop which breaks on non-zero will work well. It does, however, mean that the slowest check will be on all zero, which is worth keeping in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With