Skip to main content
Code Review

Return to Answer

replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link

You declared sizesMap[11], but initialized it with 13 entries. If that works at all, it might be overwriting some neighbouring memory. You could simply write sizesMap[11] = { 0 } sizesMap[11] = { 0 }.

You declared sizesMap[11], but initialized it with 13 entries. If that works at all, it might be overwriting some neighbouring memory. You could simply write sizesMap[11] = { 0 }.

You declared sizesMap[11], but initialized it with 13 entries. If that works at all, it might be overwriting some neighbouring memory. You could simply write sizesMap[11] = { 0 }.

Source Link
200_success
  • 145.6k
  • 22
  • 190
  • 479

You declared sizesMap[11], but initialized it with 13 entries. If that works at all, it might be overwriting some neighbouring memory. You could simply write sizesMap[11] = { 0 }.

Your code would be easier to understand if you universally added n to j:

for (unsigned n = 1; n != units.size(); n++)
 for (unsigned j = n; j != units.size(); j++)
 {
 unsigned sizesMap[11] = { 0 };
 for (auto it = units.begin() + n; it != units.begin() + (j + 1); it++)
 {
 for (unsigned k = 1; k != 11; k++)
 {
 sizesMap[k] += (*it).sizes[k];
 }
 }
 //do something with sizesmap
 }

It's also more idiomatic C++ to write:

for (auto i = units.begin() + 1; i != units.end(); ++i) {
 for (auto j = i; j != units.end(); ++j) {
 unsigned sizesMap[11] = { 0 };
 for (auto it = i; it != j + 1; ++it) {
 for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {
 sizesMap[k] += it->sizes[k];
 }
 }
 //do something with sizesMap
 }
 }

Assuming that when you "do something with sizesMap", you don't overwrite any of its entries, you can build on top of the sizesMap you previously constructed.

 for (auto i = units.begin() + 1; i != units.end(); ++i) {
 unsigned sizesMap[11] = { 0 };
 for (auto j = i; j != units.end(); ++j) {
 for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {
 sizesMap[k] += j->sizes[k];
 }
 //do something non-destructive with sizesMap
 }
 }

I think you could even go further:

 unsigned sizesMap[11] = { 0 };
 for (auto i = units.begin() + 1; i != units.end(); ++i) {
 for (auto j = i; j != units.end(); ++j) {
 for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {
 sizesMap[k] += j->sizes[k];
 }
 //do something non-destructive with sizesMap
 }
 for (size_t k = 1; k != sizeof(sizesMap) / sizeof(sizesMap[0]); k++) {
 sizesMap[k] -= i->sizes[k];
 }
 }

Is the compiler doing all that for you automatically? It seems a bit freaky that it could be smart enough to do so. The only way to tell what the optimizer is doing is to inspect its assembler output.

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /