What is the most efficient way to manipulate a std :: strings two-dimensional dynamic array in memory?

I am currently using.

std::vector<std::vector<std::string> > MyStringArray

But I have read here a few comments about SO that prevent the use of nested vectors based on efficiency.
Unfortunately, I have yet to see examples of alternatives to the nested vector for such a situation.

+5
source share
3 answers

Here's a simple dynamic 2D array with a custom 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());
  }
};

Using:

TwoDArray arr(5); // five columns per row
arr.set_number_of_rows(20);
arr(0, 3) = "hello";
arr(17,2) = "world";

. , , , ; .

(i,j), [i][j].

+3

, . , , ; ( ++ 0x STL).

+1

The most efficient way is probably to have the strings adjacent in memory (separated by null terminators) and have a continuous array of links to each line and another continuous array of links to each array.

This is to maintain the location and efficient use of the cache, but ultimately it depends on how you access the data.

0
source

All Articles