c++vectorconcatenationpush-back

what is the difference between vector.push_back() and inserting element like Vector[index]?


class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        
      int n=nums.size();
        vector<int> ans(2*n);
        for(int i=0;i<2*n;i++)
        {
            if(i<n)
            {
                ans.push_back(nums[i]);
            }
            else
            {
                ans.push_back(nums[i-n]);
            }  
        }
        return ans;
        
    }
};

This above code is not giving appropriate ans.

while below code is working fine.

class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        
      int n=nums.size();
        vector<int> ans(2*n);
        for(int i=0;i<2*n;i++)
        {
            if(i<n)
            {
                ans[i]=nums[i];
            }
            else
            {
                ans[i]=nums[i-n];
            }  
        }
        return ans;
        
    }
};

Solution

  • When you create the vector you have specified a size already (usually not done with vectors) so your vector already filled with ints that have been set to 0. So when you use ans[i] = nums[i]; you are simply editing one of the already existing elements stored in the vector.

    Usually when you create a vector you create it as an empty one by doing vector<int> ans; or vector<int>* ans = new vector<int>(); (if you want to create it on the heap) and then add a new element to it using ans.push_back(value); which will add the element to the back/end of the vector.