Rich
Rich

Reputation: 1851

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.

Upvotes: 2

Views: 3491

Answers (3)

PHE
PHE

Reputation: 81

Note that the vectors vector<int> are not guaranteed to be in a contiguous block of memory, therefore one has to iterate, in whatever form, through the 1st dimension of the 2D std vector to do the reassignments.

Upvotes: 0

Mark Lakata
Mark Lakata

Reputation: 20878

I know I am going to get flack for this answer, but I am sure there is nothing faster:

for(auto& x : v) memset(&x[0],0,sizeof(int)*x.size());

memset is highly optimized for setting to 0.

Upvotes: 1

Barry
Barry

Reputation: 303337

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

Upvotes: 5

Related Questions