What do you think of my code, is it well written? Any tips or is it "perfect"? #include…
- User
What do you think of my code, is it well written? Any tips or is it "perfect"?
#include #include #include #include #include
int main() { std::vector<std::vector> vectors = { {1.0, 2.0, 3.0, 4.0, 5.0}, {0.5, 1.5, 2.5, 3.5, 4.5}, {2.0, 4.0, 6.0, 8.0, 10.0}, {1.1, 2.2, 3.3, 4.4, 5.5}, {0.1, 0.2, 0.3, 0.4, 0.5} };
for (auto& vec : vectors) { double total_sum = std::accumulate(vec.begin(), vec.end(), 0.0); // Normaliser le vecteur std::transform(vec.begin(), vec.end(), vec.begin(), [total_sum](double x) { return x / total_sum; }); // Ajuster le dernier élément double adjusted_sum = std::accumulate(vec.begin(), vec.end() - 1, 0.0); vec.back() = 1.0 - adjusted_sum; } // Afficher les vecteurs normalisés for (size_t i = 0; i < vectors.size(); ++i) { std::cout << "Vecteur " << i + 1 << ": "; for (double val : vectors[i]) { std::cout << std::fixed << std::setprecision(15) << val << " "; } std::cout << std::endl; // Vérifier la somme double sum = std::accumulate(vectors[i].begin(), vectors[i].end(), 0.0); std::cout << "Somme du vecteur " << i + 1 << ": " << sum << std::endl; } return 0;}
- Assistant
Your code is quite clean and does the job. A few minor suggestions to make it more robust, maintainable and “modern C++”:
-
Handle edge‑cases
- What if a vector sums to 0? You’ll end up dividing by zero.
- You may also get slight negative rounding on the last element if the first N−1 sums to e.g. 1.000000000000001.
-
Factor out normalization into a function
This makes yourmain()smaller and gives you a place to unit‑test the logic in isolation. -
Prefer
std::size_t(or evenauto) for indices and avoid magic constants. -
Use
const/ references where possible, and guard against empty vectors. -
(Micro‑opt) Reserve capacity or use
std::array<double,5>if the size is always 5.
Here’s an example refactoring:
#include <iostream> #include <vector> #include <numeric> #include <iomanip> #include <stdexcept> // Normalize so sum(vec) == 1. // If sum == 0, throws; always corrects the last component to absorb rounding. void normalize(std::vector<double>& vec) { if (vec.empty()) { throw std::invalid_argument("Cannot normalize an empty vector"); } const double total = std::accumulate(vec.begin(), vec.end(), 0.0); if (total == 0.0) { throw std::domain_error("Vector sum is zero; cannot normalize"); } // First pass: scale everything for (double& x : vec) { x /= total; } // Second pass: adjust last element to exactly 1 - sum(first N-1) double partial = std::accumulate(vec.begin(), vec.end() - 1, 0.0); vec.back() = 1.0 - partial; } int main() { std::vector<std::vector<double>> vectors = { {1.0, 2.0, 3.0, 4.0, 5.0}, {0.5, 1.5, 2.5, 3.5, 4.5}, {2.0, 4.0, 6.0, 8.0, 10.0}, {1.1, 2.2, 3.3, 4.4, 5.5}, {0.1, 0.2, 0.3, 0.4, 0.5} }; for (auto& vec : vectors) { try { normalize(vec); } catch (const std::exception& e) { std::cerr << "Normalization error: " << e.what() << "\n"; continue; } // Display std::cout << "Normalized: "; for (double v : vec) { std::cout << std::fixed << std::setprecision(15) << v << " "; } double check = std::accumulate(vec.begin(), vec.end(), 0.0); std::cout << "\nSum = " << std::setprecision(15) << check << "\n\n"; } return 0; }Why this is “better”:
- You have a single, testable
normalize()routine. - You guard against divide‑by‑zero and empty data.
- You keep
main()focused on I/O.
Aside from that, your original code is already quite idiomatic (using
accumulate,transform, range‑for, etc.). It’s “perfect” for many use‑cases—these tweaks just help it scale and fail gracefully. 👍 -
- User
Do I actually need the "second pass"?
- Assistant
You only need that “second pass” if:
- You care about forcing the sum to be exactly 1.0 (within your printed precision), and
- You’re willing to give up a bit of “fairness” in how rounding error is distributed (i.e. dumping all the tiny leftover into the last element).
If you’re happy with a sum like 0.999999999999998 or 1.000000000000002, you can drop it altogether and just do:
double total = std::accumulate(vec.begin(), vec.end(), 0.0); if (total != 0.0) { std::transform(vec.begin(), vec.end(), vec.begin(), [total](double x){ return x/total; }); }That’s a single pass (well, two if you count the accumulate + transform separately) and you get a “normalized” vector in the usual sense.
―― or ――
If you still want to avoid a full two‑pass over the data but guarantee the sum is exactly 1, you can do it in one loop:
void normalize_in_one_pass(std::vector<double>& v) { if (v.empty()) throw std::invalid_argument{"Empty vector"}; double total = std::accumulate(v.begin(), v.end(), 0.0); if (total == 0.0) throw std::domain_error{"Sum is zero"}; double partial = 0.0; for (size_t i = 0; i + 1 < v.size(); ++i) { v[i] = v[i] / total; partial += v[i]; } // dump ALL leftover into the last element v.back() = 1.0 - partial; }Benefits of this approach:
- You still only touch each element once (plus a tiny check on the last).
- You guarantee sum(vec) == 1.0 exactly (modulo floating‑point representation of 1.0 itself).
- You avoid a separate
std::transformand a separateaccumulateovervec.begin()…vec.end()-1.
If, however, you don’t have a hard requirement that the printed sum be exactly 1.000000000000000, the extra “adjust last element” step is purely a nicety for presentation / downstream invariants and can safely be omitted. 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.