I want to write a function that iterates through a list, but takes two elements if they equal a target.
The logic could be to have two loops; first iterate through list and see if any element + the first = target, then second, then third
etc..
int i;
int max = list.size;
for(i=0; i<=max; i++)
{
if()
}
in c++
int i;
int max = resistors.size();
int curr;
for(curr = 0; curr<=resistors.size(); curr++)
{
for(i=1; i<=max; i++)
{
if((resistors[curr]+resistors[i])==target){
ComposeSerial(resistors[curr], resistors[i]);
}
}
}
i believe one thing is missing to make sure that it goes through again?
It might help if you thought about it slightly differently. You said “first iterate through list and see if any element + the first = target”. What if you phrased it as “Iterate through the list and see if the current element + any other element in the list = target”. All I’ve done is consolidated your placement of “the first, then second, then third etc…” into the “current element”.
Your original phrasing suggests only one loop, with some magic to get the first element, then the second, etc. This reversed phrasing suggests two loops: one to get each element, then an inner loop to test the current element with every other element in the list. Hopefully that way of thinking will clear up any confusion.
Edit:
Since this didn’t clear up all the confusion, I’m going to add some pseudocode:
One obvious optimization would be for the inner loop to start after the element from the outer loop, like so:
Depending on the problem, you may want to include the outer element at the start of the inner loop:
To write the actual code, grab your textbook, or the nearest C++ reference, or go to cplusplus.com, look up the documentation for the specific container type you’re using, and determine the best way to iterate through your elements from there.
Edit 2 – Response to Edited Question
Thanks for the updated question. The only issues I see here are, as @leetNightshade pointed out in the comment, the inner loop should start at
curr + 1(orcurr, if you want to allow the test for an element with itself, which you probably don’t), and your loops should terminate whencurr < resistors.size(), andi < max, respectively. Otherwise, you will include one element past the end of your list in your loop, which will have nasty consequences.