0

I've tried something like this:

vector<bool> x(10, 0);
vector<vector<bool> > hello(10, x);

/*some modifications on hello*/

memset(&hello, 0, sizeof(hello));

And my program compiles, but it breaks. Any idea how I can do this operation as quickly as possible? I know that the memset probably isn't working because of the nested vector, but I'm not sure how to accomplish this task.

  • is the second dimension always 10 in size? I mean always always? – Yakk - Adam Nevraumont Jan 04 '14 at 04:31
  • 1
    You should be careful using `memset` in c++, see http://stackoverflow.com/questions/1975916/should-c-programmer-avoid-memset Even if it didn't result in a runtime error, you would have best case cleared the outer vector completely and leaked some memory on the way. –  Jan 04 '14 at 04:34

3 Answers3

1

I would use this, which reuses the x variable you declared in the question.

std::fill(hello.begin(), hello.end(), x);
Sam Harwell
  • 94,937
  • 19
  • 203
  • 272
1
for(auto& bv : hello) 
    std::fill(begin(bv), end(bv), false);

Or if you want to use x as the prototype

std::fill(begin(hello), end(hello), x);
111111
  • 15,074
  • 6
  • 41
  • 58
0

With the code you have, I'd write …

for( auto& v : hello ) { v = x; }

assuming x has remained as all-zeros. It's clear enough and avoids dragging in <algorithm>.

Hewever, it will probably be faster to change the representation of your bit matrix, from a vector of vectors to a single vector, or if it's fixed size, to a single bitset.

Cheers and hth. - Alf
  • 138,963
  • 15
  • 198
  • 315