int result{};
if (vec.size() > 1) {
for (size_t i=0; i< vec.size()-1; ++i)
for (size_t j=i+1; j< vec.size(); ++j)
result = result + vec.at(i) * vec.at(j);
}
return result;
Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
This may help you to visualize and understand the code better:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int result{};
if (vec.size() > 1)
{
for (size_t i = 0; i < vec.size() - 1; ++i)
{
for (size_t j = i + 1; j < vec.size(); ++j)
{
result += vec[i] * vec[j];
}
}
}
return result;
Line 1 defines the variable "result" and the {}s set it to zero.
Line 3 makes sure the vector is large enough to to let the for loops work .
The outer for loop goes to the vectors size -1, so that it will not exceed the size of the vector. This is because the inner for loop starts at "i + 1" and this keeps "j" from going past the end of the vector.
The inner for loop goes from "i + 1 to vector.size()" so that you are always multiplying the outer for loop element by what is left in the vector.
seeplus's response shows what the two loops are doing.
The two for loops will limit how far they will travel through the vector, so the ".at()" function is just extra overhead that is not needed here. Using the []s is all that is really needed.
Line 9 is just a shorthand way of writing this. Both versions work the same way.