-2

I have a code flush[*it % 4].push_back(*(it++) /= 4); and it was meant to push_back the new value(old value/4) before incrementing the it iterator, is it right like this or how to do it the fastest way to get value from iterator, divide it by 4, store it, use the new value in push_back and then increase the iterator?

Lukas Salich
  • 959
  • 2
  • 12
  • 30

1 Answers1

5

That's pretty nasty. Does it get incremented before, or after, *it % 4? Protip: It's not defined, so your code doesn't have well-defined results. This is very bad. In addition, it's generally a mess- you've made two reads and a write to one variable, and an assignment, and a function call, and an index. That's a lot for one expression.

Use several statements to implement your logic.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • It starts on my list.begin() and is used in loop: while(it != tableAndHand.end()) flush[*it % 4].push_back(*(it++) /= 4); and the it has to be incremented after *it%4. – Lukas Salich Sep 16 '12 at 18:03
  • The only way to ensure that is to split up your expression. – Puppy Sep 16 '12 at 18:06
  • So you saying, that {flush[(*it)%4].push_back((*it)/4); ++it; } will be same fast and better in something? – Lukas Salich Sep 16 '12 at 18:14
  • @LukasSalich: Absolutely. But don't take our words for it. Try it. See what the machine instructions are and see if you can do better by hand. In reality trying to do this kind of macros optimization is a waste of time (The compiler will always be better than you the human). Write clean clear code and worry about the algorithm not individual statements (Here you can beat the compiler). – Martin York Sep 16 '12 at 20:33
  • @LokiAstari Ok, best explanation ever :) I am also trying to optimize really everything, because I go through about 10bil of iterations. – Lukas Salich Sep 16 '12 at 22:19