Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which data structure is better for an array of std string

I need a structure as follow:

Figure1

The structure must hold fixed size std::strings so that the number of its elements is finit (100 - 10000000).

I would like to be able to access each element randomly as follow:

std::string Temp = MyStrcuture[i];

or

MyStrcuture[i] = std::string Temp;

I have to use 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?
like image 722
m.r226 Avatar asked Dec 03 '22 23:12

m.r226


2 Answers

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

Vector is the best fit for your requirements. It supports index-based element access as the elements are stored in continuous memory addresses, and 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

like image 68
Saurav Sahu Avatar answered Dec 06 '22 11:12

Saurav Sahu


Well, since your string have fixed size, if you don't have dedicated requirement when processing string and have enough free memory for contiguous allocation. You can use std::array< char, 400 > or std::unique_ptr< char* > instead of std::string.

  1. You have to manage memory in C way. consider smart pointer
  2. std::queue doesn't have random access, Access c++ queue elements like an array

  3. std::vector is suitable if the number of string will be changed. However, the clear() function just call the destructor of elements, not free vector allocated memory (you can check the capacity after clear).

  4. After reading boost documentation. The random access circular buffer is suitable if your number of string have an upper limit (that you said 10 millions). But its a waste of memory if actually you have so few strings. So I suggest to use with smart pointer.

  5. If your number of string are fixed and unchanged from the beginning. You can have a look at C++11 array container

like image 42
khôi nguyễn Avatar answered Dec 06 '22 12:12

khôi nguyễn