-3

This function is intended to take a vector with x,y value pairs of the form {x1, x2, x3, y1, y2, y3} and return a vector with the values shuffled as such {x1, y1, x2, y2, x3, y3}. The size of the vector is 2*n, where n is the number of x values/y values respectively. By using print statements inside the function, I've already determined that the algorithm works.

    vector<int> shuffle(vector<int>& nums, int n) {
        vector<int> temp;
        temp.reserve(2*n);
        int xCounter = 0;
        int yCounter = n;
        
        for (int i=0; i<2*n; i+=2){
            
            // populate arr x val
            temp[i] = (nums[xCounter]);
            // populate arr y val
            temp[i+1] = (nums[yCounter]);
            ++xCounter;
            ++yCounter;
        }
        
        return temp;
    }

int main()
{
    vector<int> yoMomma = {1,2,3,1,2,3};
    vector<int> ans;
    ans = shuffle(yoMomma,yoMomma.size()/2);

return 0;
}
wjtwise
  • 19
  • 6
  • 2
    [`reserve`](https://en.cppreference.com/w/cpp/container/vector/reserve) doesn't change the size of the vector, so all of your vector accesses are invalid. You want to use [`resize`](https://en.cppreference.com/w/cpp/container/vector/resize) – Kevin Feb 06 '23 at 23:23
  • 1
    Read through your code. Inside the function, at what point do you change it's size? – ChrisMM Feb 06 '23 at 23:23
  • 2
    Does this answer your question? [std::vector::resize() vs. std::vector::reserve()](https://stackoverflow.com/questions/13029299/stdvectorresize-vs-stdvectorreserve) – Kevin Feb 06 '23 at 23:24
  • You seem to have skipped some important parts of your beginners learning material. – Some programmer dude Feb 06 '23 at 23:25
  • Thanks everyone. Most often it is the little common sense mistakes that we skip over, so I appreciate the extra set of eyes. – wjtwise Feb 07 '23 at 01:15
  • The vector "temp" was printing correct values while I was trying to debug with "cout << temp[i]", so I thought it was working until the function return statement was called. – wjtwise Feb 07 '23 at 01:26

1 Answers1

0

You called reserve, not resize, so your vector isn't actually increased in size, just capacity (pre-allocated memory that can hold elements in the future without having to reallocate). But that makes all your indexing assignments illegal; the vector still has a length of 0, you can't assign to any index. It happens to work because the reserve ensures there is memory there, but said memory would never be properly destructed (so it's a good thing you're using primitive types without destructors).

Change your loop to:

    for (int i=0; i<n; ++i){            
        // populate arr x val
        temp.push_back(nums[i]);
        // populate arr y val
        temp.push_back(nums[i+n]);
    }

pushing new values onto the end, and saving a couple unnecessary variables, rather than indexing.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271