c++vector

Check if entire vector is zero


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++;
        }

Solution

  • 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; });