Skip to content

Commit b59e8f0

Browse files
committed
Use plain array for estimate_halfway program
We were using std::vector and pushing new values onto the end, but a plain C-style array is sufficient for this example, and doesn't require dynamic allocation. Resolves #1523
1 parent 387baf8 commit b59e8f0

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

books/RayTracingTheRestOfYourLife.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -938,12 +938,12 @@
938938
}
939939

940940
int main() {
941-
unsigned int N = 10000;
941+
const unsigned int N = 10000;
942+
sample samples[N];
942943
double sum = 0.0;
943944

944945
// Iterate through all of our samples.
945946

946-
std::vector<sample> samples;
947947
for (unsigned int i = 0; i < N; i++) {
948948
// Get the area under the curve.
949949
auto x = random_double(0, 2*pi);
@@ -953,11 +953,11 @@
953953

954954
// Store this sample.
955955
sample this_sample = {x, p_x};
956-
samples.push_back(this_sample);
956+
samples[i] = this_sample;
957957
}
958958

959959
// Sort the samples by x.
960-
std::sort(samples.begin(), samples.end(), compare_by_x);
960+
std::sort(samples, samples + N, compare_by_x);
961961

962962
// Find out the sample at which we have half of our area.
963963
double half_sum = sum / 2.0;

src/TheRestOfYourLife/estimate_halfway.cc

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ bool compare_by_x(const sample& a, const sample& b) {
2727

2828

2929
int main() {
30-
unsigned int N = 10000;
30+
const unsigned int N = 10000;
31+
sample samples[N];
3132
double sum = 0.0;
3233

3334
// Iterate through all of our samples.
3435

35-
std::vector<sample> samples;
3636
for (unsigned int i = 0; i < N; i++) {
3737
// Get the area under the curve.
3838
auto x = random_double(0, 2*pi);
@@ -42,11 +42,11 @@ int main() {
4242

4343
// Store this sample.
4444
sample this_sample = {x, p_x};
45-
samples.push_back(this_sample);
45+
samples[i] = this_sample;
4646
}
4747

4848
// Sort the samples by x.
49-
std::sort(samples.begin(), samples.end(), compare_by_x);
49+
std::sort(samples, samples + N, compare_by_x);
5050

5151
// Find out the sample at which we have half of our area.
5252
double half_sum = sum / 2.0;

0 commit comments

Comments
 (0)