DEV Community

Cover image for DILI #4
DHDucky
DHDucky

Posted on

DILI #4

VECTOR

Vector! You might heard of this name if you are really into math or into "Minions". But in C++, it's not what you might think. It's similar to an array ... BUT BETTER. Do you ever find it annoying that you have to type in that 100 or 1000 or even 10000 for the size of the array? Well Vector got you covered with his "Shrink ray".

Image description

Just like in the film, Vector in C++ can resize itself depending on the number of elements you add in or take away. Which is really frickin' convenient! And it's even in STL so no need to call for it. The only downside is it's a bit lengthy to initialize:

vector< object_type > vector_variable_name;
Enter fullscreen mode Exit fullscreen mode

Here are a few frequently used fuctions for vectors all of which are used via vector_name.funcion():

size() - self explanatory
assign() – It assigns a new value to the existing elements of the vector.
push_back() – It pushes the element from back in the vector.
pop_back() – It removes elements from the back of the vector.
insert() – It inserts an element before a specified element in the vector.
erase() – It is used to remove elements from a specified element or a range in the vector.
swap() – It is used to swap the contents of two vectors of the same datatype. The sizes of vectors may differ.
clear() – It is used to remove all the elements from the vector.

For demonstration purposes, this is me after fidgeting for a bit of time to do this problem on LeetCodes:

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Input: nums1 = [1], m = 1, nums2 = [2,7,6], n = 0
Output: [1,2,6,7]
Enter fullscreen mode Exit fullscreen mode

My solution:

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) 
{
        for (int i = 0; i < n; i++){
            nums1.push_back(nums2[i]);
        }
        sort(nums1.begin(), nums1.end());
}
Enter fullscreen mode Exit fullscreen mode

Very sort and definitely brute force but hey, I used vectors. Anyways, if you can do better, better solutions in the comments are very welcomed!

As always, I need all the advices I can get on coding or blog-writing or even life (this would be most appreciated)!

REFERENCE:
GeeksforGeeks
Chapter 11.17
The Problem above

Top comments (0)