2

I am attempting to move away from std::vector<std::vector<int>> types and use boost::multi_array in its place. I am struggling how to initialize such data members though.

I used to have a class thus:

class problemdata{ std::vector<std::vector<int>> data; }; 

Then, at run time, based on values of user inputs ui1 and ui2, I would do the following to create storage for data.

std::vector<int> temp(ui2); for(int i = 0; i < ui1; i++) data.push_back(temp); 

How can I do something similar with boost::multi_array ? All examples in the official documentation seem to have compile time constants defining dimensions. https://www.boost.org/doc/libs/1_69_0/libs/multi_array/doc/user.html

I, however, need to declare an empty container first, read user data and only then accordingly populate the container.

1

1 Answer 1

2

Example:

Live On Coliru

#include <boost/multi_array.hpp> #include <fmt/ranges.h> struct Demo { boost::multi_array<int, 2> data{std::array{0, 0}}; // starts out empty void init(uint ui1 = 0, uint ui2 = 0) { // data.resize(std::array{ui1, ui2}); } void print() const { if (data.empty()) fmt::print("Data is empty\n"); else fmt::print("Data is {}\n", data); } }; int main() { Demo d; d.print(); d.init(3, 6); d.print(); d.init(2, 4); d.print(); d.init(/*0, 0*/); d.print(); } 

Printing

Data is empty Data is [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] Data is [[0, 0, 0, 0], [0, 0, 0, 0]] Data is empty 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. In data.resize(std::array{ui1, ui2}); is it possible to default initialize the ui1 x ui2 entries to some userdefined value, say -1?
Didn't I show that? My code defaults it to 0 (because unsigned -1 is MAXINT and you really don't want that as a default)
In your example, the multi_array stores integers from what I understand. Instead of all entries at birth being initialized to 0, I want them to be initialized to -1 because that has special meaning in my application. uint was for the dimensions of the matrix which of course make no sense being negative or MAXINT.
Alternatively, I as the user would have to do like so: coliru.stacked-crooked.com/a/abe37c3f624a67d3 I'd like to avoid manual iterating as much as possible and use the constructor (if available) which allows me to initialize to my user defined value at birth itself.
Oh. I misunderstood (I thought you wanted to default ui1 and ui2). Yes, you can initialize the data. E.g. std::fill_n(data.origin(), data.num_elements(), -1);. See it Live On Coliru again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.