C ++ - STL Vector Question

Is there any way to do std::vectorfaster on reserving + resizing?

I would like to achieve performance that would be somewhat equivalent to regular C arrays.

See the following code snippets:

TEST(test, vector1) {
   for (int i = 0; i < 50; ++i) {
      std::vector<int> a;
      a.reserve(10000000);
      a.resize(10000000);
   }
}

TEST(test, vector2) {
   for (int i = 0; i < 50; ++i) {
      std::vector<int> a(10000000);
   }
}

TEST(test, carray) {
   for (int i = 0; i < 50; ++i) {
      int* new_a = new int[10000000];
      delete[] new_a;
   }
}

The first two tests are twice as slow ( 4095 ms vs 2101 ms) and, obviously, this happens because it std::vectorresets the elements in it. Any ideas on how to avoid this?

Or maybe there is a standard (boost?) Container that implements an array with a fixed size and heap?

thank

+3
source share
5 answers
+11
+2

? , microsoft , .

+2
+1

, , . , , , , , , .

boost :: scoped_array is one solution. There is no way to make the vector not initialize the elements that it stores. The other is std :: deque if you don't need a contiguous block of memory. deque can be significantly faster than a vector or a dynamically allocated array with the same number of elements as it, because it creates smaller blocks of memory that operating systems tend to do better with maintaining caching.

+1
source

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


All Articles