0

I'm new to C++ and I can't understand this code. It's really hard. Can someone please explain this to me?

#include <vector>
using namespace std;

int calculate_pairs(vector<int> vec) {
    //----WRITE YOUR CODE BELOW THIS LINE----
    int result{};
    for(size_t i = 0; i < vec.size(); ++i)
        for(size_t j = i + 1; j < vec.size(); ++j) /* what is size_t and vec.size? what does this do j = i + 1;*/
            result = result + vec.at(i) * vec.at(j); /*what does this do?*/
    return result;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • [for loops](https://www.w3schools.com/cpp/cpp_for_loop.asp) [vectors](https://www.codecademy.com/learn/learn-c-plus-plus/modules/learn-cpp-vectors/cheatsheet) In short: vectors are containers. size() gives you the size of the container. For loops are used to do something multiple times. – cershif Dec 13 '21 at 03:49
  • `size_t` is an unsigned integer type. Don't get too caught up on it. Just imagine it is `int`. Even though it's not, and there are some traps with thinking of it that way, it'll be just fine to do so as you grapple to understand the language basics. On that note, it's highly recommended to read material that's exclusively written to introduce you to this stuff without freaking you out. Just diving into C++ and "figuring it out" is not practical for most people. Treat yourself with an introductory book on C++. – paddy Dec 13 '21 at 03:55
  • 1
    The best place to learn about these things is in a [good C++ book](https://stackoverflow.com/questions/388242/). StackOverflow is a Q&A site, not a tutorial service. – Remy Lebeau Dec 13 '21 at 04:45
  • Do you understand what this code does? This sums up all of the distinct pairs of numbers in the vector. `vec.at(i)` is more traditionally written `vec[i]` and just returns the i-th element of the vector. – Tim Roberts Dec 13 '21 at 04:47
  • It calculates the second power of the sum of the vector elements, in an awkward “polynomial multiplication” style. – Andrej Podzimek Dec 13 '21 at 06:52
  • thank you guys for explaining this to me :) – ali al zamili Dec 14 '21 at 22:58

0 Answers0