Search code examples
c++c++11vector

Reset vector of vector (2D array) to zero


I am using vector of vector to simulate a 2D array. In order to reuse this 2D array, sometimes I need to reset all its elements to zero or some default value. I know for a simple 1D vector I can do:

std::fill(v.begin(), v.end(), 0);

How to do that efficiently for a vector<vector<int>>? I hope to find a solution without using for loops but more akin to some memset variant. I also don't want to incur any memory allocation and deallocation since my intent was to reuse the existing allocated memory.

Note that I am assuming each vector's size is fixed and known to me: vector<vector<int>> v(const_max_size, vector<int> (const_max_size, 0));. How to reset v's elements to zero?

NOTE: What I mean by not using for loops is that I don't want to iterate over all the 2D elements using subscripts like v[i][j] to assign them the value.


Solution

  • I hope to find a solution without using for loops ...

    Well, either you do a loop explicitly or use something that loops implicitly. Nothing wrong with explicit loops:

    for (auto& sub : v) {
        std::fill(sub.begin(), sub.end(), 0);
    }
    

    I guess technically if you want to avoid a loop you could use:

    std::for_each(v.begin(), v.end(),
                  [](auto& sub) {
                      std::fill(sub.begin(), sub.end(), 0);
                  });