Skip to content

Listing 3.12: No need to use vectors and dynamic (re)allocation #1523

@dimitry-ishenko

Description

@dimitry-ishenko

In Listing 12 we are using std::vector<sample> samples to collect random samples. With N = 10000 this will most likely cause multiple memory re-allocations (IIRC vectors usually grow by powers of 2).

There is absolutely no reason to use std::vector<> in this case. The two alternatives are:

  1. Use plain-old C-style array:
 int main() {
-    unsigned int N = 10000;
+    const unsigned int N = 10000;
     double sum = 0.0;
 
     // iterate through all of our samples
-    std::vector<sample> samples;
+    sample samples[N];
     for (unsigned int i = 0; i < N; i++) {
         // Get the area under the curve
         auto x = random_double(0, 2*pi);
@@ -40,11 +38,11 @@ int main() {
         sum += p_x;
         // store this sample
         sample this_sample = {x, p_x};
-        samples.push_back(this_sample);
+        samples[i] = this_sample;
     }
 
     // Sort the samples by x
-    std::sort(samples.begin(), samples.end(), compare_by_x);
+    std::sort(std::begin(samples), std::end(samples), compare_by_x);
 
     // Find out the sample at which we have half of our area
     double half_sum = sum / 2.0;
  1. Use "modern" std::array<> introduced in C++11:
 int main() {
-    unsigned int N = 10000;
+    const unsigned int N = 10000;
     double sum = 0.0;
 
     // iterate through all of our samples
-    std::vector<sample> samples;
+    std::array<sample, N> samples;
     for (unsigned int i = 0; i < N; i++) {
         // Get the area under the curve
         auto x = random_double(0, 2*pi);
@@ -40,7 +38,7 @@ int main() {
         sum += p_x;
         // store this sample
         sample this_sample = {x, p_x};
-        samples.push_back(this_sample);
+        samples[i] = this_sample;
     }
 
     // Sort the samples by x

This renders easier-to-understand code for non-C++ students who are not familiar with std::vector<>, templates, push_back(), etc.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions