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
  • 97,721
  • 20
  • 209
  • 280
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,686
  • 6
  • 47
  • 62
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
  • 142,714
  • 15
  • 209
  • 331