2021年2月5日星期五

C++ Changing array element changes another element

So I have a 2d array of vectors, and apparently changing the element at an index can also change the one above it. Here is the code that is causing me issues:

/// Initialization  std::vector<int> x_array;  std::vector<int> y_xarray[2000][2];  int ymin=200;    //Problematic code    x_array.clear(); //x_array is an std::vector<int>    x_array.push_back(594);    y_xarray[251-ymin][0]=x_array; //y_xarray is a 2d array of vectors. Assigning element at index 251-ymin    x_array.clear();    std::cout<<y_xarray[251-ymin][0][0]<<std::endl; //prints 594    x_array.push_back(256);    y_xarray[250-ymin][xarray_ind[250-ymin]]=x_array; //Assigning element at 250-ymin index    std::cout<<y_xarray[251-ymin][0][0]<<std::endl; //prints 256  

The std::cout shows that the vector at 251-ymin index changes from the assignment of the 250-ymin index. These indices seem to be the only ones that have this issue, but idk what is up with this case.

Solved, with answer below. Pretty much I am stupid.

https://stackoverflow.com/questions/66072337/c-changing-array-element-changes-another-element February 06, 2021 at 08:20AM

没有评论:

发表评论