Search code examples
c++vectorgarbagepush-back

garbage values for vector push_back


I'm trying to assign an array's values to a vector. It seems to be working fine for one vector, but when I do it for a second, I'm getting back garbage values. I cout the number and I know it's correct, but it's not assigning correctly. I don't understand because it's working fine for the first vector.

int sorted[] = {0,1,2,3,4,5,6,7,8,9,10};

// make two smaller arrays, do this untill they are a base case size; 
void split(int *dataIN, int dataSize){
    // new data will be broken up into two vectors with each half of the 
    // original array. These will be size firstHalfSize and secondHalfSize.     
    int firstHalfSize; 
    int secondHalfSize;     
    vector<int> firstHalf; 
    vector<int> secondHalf;     
    // test to see if array in is odd or even   
    bool isOdd; 
    if (dataSize%2 == 1){
        isOdd = true;   
    }else if (dataSize%2 == 0){
        isOdd = false; 
    }   
    // determine length of new vectors
    // second half is firstHalf + 1 if odd.     
    firstHalfSize = dataSize/2; 
    if (isOdd){
        secondHalfSize = firstHalfSize + 1; 
    }else if (!isOdd){
        secondHalfSize = firstHalfSize; 
    }           
    // assign first half of dataIn[] to firstHalf vector    
    cout << "firs: " << firstHalfSize << endl;
    for (int i = 0; i < firstHalfSize; i++){
        cout << "a: " << dataIN[i] << endl;// make sure i have the right number 
        firstHalf.push_back(dataIN[i]);// assign    
        cout << "v: " << firstHalf[i] << endl;// make sure assigned correctly   
    }   
    // do the same for second half  
    cout << "second: " << secondHalfSize << endl;   
    for (int i = firstHalfSize; i < (firstHalfSize+secondHalfSize); i++){
        cout << "a: " << dataIN[i] << endl; 
        secondHalf.push_back(dataIN[i]);    
        cout << "v: " << secondHalf[i] << endl; 
    }   

}


int main(void){
    split(sorted, sizeof(sorted)/sizeof(int));  
    return 0;
}

This is my result. As you can see the first vector push_back went fine and the array values (after "a: ") are also correct.

firs: 5
a: 0
v: 0
a: 1
v: 1
a: 2
v: 2
a: 3
v: 3
a: 4
v: 4
second: 6
a: 5
v: -805306368
a: 6
v: 2
a: 7
v: -805306368
a: 8
v: 0
a: 9
v: 0
a: 10
v: 0

Solution

  • In the second case, you are indexing from firstHalfSize.

    You need to cout the values starting from index 0. For example:

    cout << "v: " << secondHalf[i-firstHalfSize] << endl;