-
Notifications
You must be signed in to change notification settings - Fork 945
Closed
Description
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:
- 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;
- 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.