I currently usestd::vector<std::vector<std::string> > MyStringArray
But I have read several comments here on SO that discourage the use of nested vectors on efficiency grounds.
Unforunately I have yet to see examples of alternatives to nested vector for a situation like this.
Here's a simple dynamic 2D array with runtime-configurable column number:
class TwoDArray
{
size_t NCols;
std::vector<std::string> data;
public:
explicit TwoDArray(size_t n) : NCols(n) { }
std::string & operator()(size_t i, size_t j) { return data[i * NCols + j]; }
const std::string & operator()(size_t i, size_t j) const { return data[i * NCols + j]; }
void set_number_of_rows(size_t r) { data.resize(NCols * r); }
void add_row(const std::vector<std::string> & row)
{
assert(row.size() == NCols);
data.insert(data.end(), row.begin(), row.end());
}
};
Usage:
TwoDArray arr(5); // five columns per row
arr.set_number_of_rows(20);
arr(0, 3) = "hello";
arr(17,2) = "world";
This is just a completely arbitrary and random example. Your real class would obviously have to contain interface methods that are suitable to what you're doing; or you might decide not to have a wrapping class at all and address the naked vector directly.
The key feature is the two-dimensional accessor operator via (i,j)
, which replaces the nested vectors' [i][j]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With