Hi, I am trying to practice some c++ problems and someone suggested leetcode, which I am failing miserably at but thats not the point of this question. I have selected a few questions and they have said they contains arrays, but when I look at the code, (unless I am misreading it) there are no arrays but instead vectors. I have not covered vectors yet in my study of c++ so i do not know anything about them, so I am wondering are they just another array? I have posted one of the questions below and the code it gives. If I am maybe misunderstanding the code and it does contain an array, please let me know. I am really struggling with these problems, I barely understand what they are asking me to do.
Question
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
1 2 3 4 5 6 7 8 9
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
for(i = 0; i < runningSum.length(); i++)
{
}
}
};
I guess that vectors probably go down as "arrays on steroids". They are basically the contiguous storage that arrays are, together with a whole plethora of functions to do clever things with them. Some nice things:
- you can address them exactly like normal arrays: nums[0], nums[1], etc ...
- they carry their size with them;
- they can be dynamically resized.
They are part of the standard template library, which is a powerful, and highly-optimised collection of containers.
Thank you for the answers, and the explanations. I will check out the links provided. The book i am learning from is old, so i do not think it covers vectors, are they new? So the links will be useful.
Gando, that is all the code that was provided by the site to complete the problem, I think it is the name of the function though, but I could be mistaken.
Vectors are not new. They aren't as old as C++ itself, but C++ has been around since the '80s (before it was standardized), and the Standard Template Library (STL) was developed around 1993, which became part of the standard library once C++ was standardized in 1998.
But many books, especially older ones, still teach C++ as being "C with classes" and don't really teach the C++ standard library.
Here's an example of printing the partial sum of a vector:
#include <iostream>
#include <vector>
using std::vector;
int partial_sum(const vector<int>& nums, int max_index)
{
int sum = 0;
for (int i = 0; i < (int)nums.size() && i < max_index; i++)
{
sum += nums[i];
}
return sum;
}
int main()
{
vector<int> vec(5); // = {1, 2, 3, 4, 5}
for (int i = 0; i < 5; i++)
{
vec[i] = i + 1;
}
std::cout << partial_sum(vec, 3) << '\n';
}