m.r226 m.r226 - 1 month ago 8
C++ Question

Which data structure is better for an array of std string

I need a structure as follow:

enter image description here

The structure must holds fixed size

std::string
s and the number of its elements is
finit
(100 - 10000000).

The only requirement which I need is the ability to access each element randomly as follow:

std::string Temp = MyStrcuture[i];


or

MyStrcuture[i] = std::string Temp;


I have to choose the fastest structure with no (possibly) memory leak.

Which one is better for me?


  1. std:string* MyStrcuture = new std::string[Nu_of_Elements];

  2. std::queue< std:string> MyStrcuture(Nu_of_Elements);

  3. std::vector< std:string> MyStrcuture(Nu_of_Elements);

  4. boost::circular_buffer< std::string> MyStrcuture(Nu_of_Elements);

  5. Your suggestion?


Answer
std::vector< std:string> MyStrcuture(Nu_of_Elements);

IMO, vector looks a good prospect for your need. It supports index-based element access as the elements are stored in continuous memory addresses. Has flexibility with size.


  1. std:string* MyStrcuture = new std::string[Nu_of_Elements]; No

    C++ STL vector vs array in the real world

  2. std::queue< std:string> MyStrcuture(Nu_of_Elements); No

    How do I get the nth item in a queue in java?
    Index-based element access is not supported.

  3. std::vector< std:string> MyStrcuture(Nu_of_Elements); Yes

    Clean-up : The vector's destructor automatically invokes the destructor of each element in the vector.

  4. Boost::circular_buffer< std::string> MyStrcuture(Nu_of_Elements); No

    Same reason as second one. Know more