What data structure is best for an std string array

I need a structure as follows:

Figure1

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

I would like to be able to access each item randomly as follows:

 std::string Temp = MyStrcuture[i]; 

or

 MyStrcuture[i] = std::string Temp; 

I have to choose the fastest structure without (possibly) a memory leak.

Which one is best 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?
+5
source share
3 answers
 std::vector< std:string> MyStrcuture(Nu_of_Elements); 

Vector best suits your needs. It supports index-based access to items, because items are stored in contiguous memory addresses and have size flexibility.


+13
source

It’s good, since your line has a fixed size, if you do not have a special requirement when processing the line and you have enough free memory for continuous allocation. You can use std :: array <char, 400> or std :: unique_ptr <char *> instead of std :: string.

  • You need to manage memory in C. read smart pointer
  • std :: queue does not have random access, access to C ++ queue elements such as an array

  • std :: vector is suitable if the number of lines is changed. However, the clear () function simply calls the element destructor, not the free vector allocated memory (you can check the throughput after cleaning).

  • After reading, raise the documentation . A round random access buffer is suitable if your line number has an upper limit (what you said 10 million). But this is a waste of memory if you really have so few lines. Therefore, I suggest using a smart pointer.

  • If your line number is fixed and unchanged from the start. You can look at the container container C ++ 11

+4
source

If the number of elements and the length are fixed and the memory is critical, you can use a simple char array that provides minimal memory overhead and fast availability. Your code will look like this:

 char* MyStructure = new char[n * 401]; memset(MyStructure, 0, n * 401); std::string Temp = MyStructure[i * 401]; // Get value strcpy(MyStructure[i * 401], Temp.c_str()); // Put value 

401 is here for 400 bytes of your string and 1 trailing zero.

0
source

Source: https://habr.com/ru/post/1259133/


All Articles