I have a function (written by someone else) which builds combination based on a set of components. Somehow, it involves bitwise shift operations to do so, but I am having difficulty in understanding it. The code is shown below:
// Declarations in the header file. vector<set<Component*, compareComponentIDs>> allScenarios; // The function. void System::buildAllScenarios() { int x, y; for (x=1; x < (1 << (int)components.size()); x++){ set<Componenet*, compareComponentIDs> curScenario; for(y=0; y < (int)components.size(); y++){ if ((x >> y) & 1){ curScenario.insert(components[y]); } } allScenarios.push_back(curScenario); } return; } Let's say the number of component is 10. Then, I think the first for loop will loop through 20 times, because bit wise shift left will multiply the number of component by 2. The second component will loop through 10 times, because there is no special operation. I have no clue what the if statement is evaluating.
Having this information, my questions are:
- How does the if statement inside of the second for loop work? What does it do?
- Why does the first for loop will iterate twice more than the number of components.
Any help would be appreciated.