Nemo
Nemo

Reputation: 461

Fill a C++ bidimensional array of objects

I'm having a simple issue with std :: fill.

First I define a 2-dimensions array of pairs.

const int NMAX = 13;                                                             
typedef pair<int, set<int>> solution;                                            
solution memo[NMAX][NMAX];    

I assume that at that stage my array is initialized with default pair constructor. Then, I would like to initialize this array without relying on a nested loop. What I am doing is this:

solution s;                                                                  
s.first = -1;                                                                                                 
std::fill( &memo[0][0], &memo[0][0] + sizeof(memo), s); 

But I get a bus error... What am I doing wrong?

Upvotes: 0

Views: 121

Answers (2)

AndyG
AndyG

Reputation: 41120

Actually we can do all of this a lot easier with std::vector:

typedef pair<int, set<int>> solution; 
solution s;                                                                  
s.first = -1;
std::vector<std::vector<solution>> memo(NMAX, std::vector<solution>(NMAX, s));

Live Demo

Unless you have some restriction against using a std::vector, it's going to be much easier to work with rather than doing a bunch of pointer math.

Edit: It's not the worst idea to use std::array either, like πάντα ῥεῖ suggested. You can avoid writing the internal loop to perform the fill yourself with a std::for_each as follows:

std::array<std::array<solution, NMAX>, NMAX> memo;
solution s;                                                                  
s.first = -1;
std::for_each(std::begin(memo), std::end(memo), [&s](std::array<solution,NMAX>& next){next.fill(s);})

Demo 2

Edit 2: If you're really masochistic and want to compute [row][column] indices yourself, then you can use a single std::array<solution, NMAX*NMAX> and take advantage of std::begin() and std::end() to call std::fill:

std::array<solution, NMAX*NMAX> memo;
solution s;                                                                  
s.first = -1;
std::fill(std::begin(memo),std::end(memo), s);

Demo 3

Upvotes: 1

Jarod42
Jarod42

Reputation: 217810

Your end pointer is wrong, you mean:

std::fill(&memo[0][0], &memo[0][0] + sizeof(memo) / sizeof (solution), s);

as sizeof(memo) is NMAX * NMAX * sizeof (solution).

Upvotes: 2

Related Questions