向量push_back的垃圾值

时间:2014-12-06 06:56:01

标签: c++ vector garbage push-back

我正在尝试将数组的值分配给向量。对于一个向量似乎工作正常,但是当我做了一秒钟时,我正在回到垃圾值。我知道这个号码,但我知道它是正确的,但它没有正确分配。我不明白,因为它适用于第一个矢量。

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;
}

这是我的结果。正如你所看到的那样,第一个向量push_back很好,数组值(在“a:”之后)也是正确的。

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

3 个答案:

答案 0 :(得分:4)

在第二种情况下,您要从firstHalfSize建立索引。

您需要输入从索引0开始的值。例如:

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

答案 1 :(得分:2)

您正在使用变量firstHalfi从0迭代到firstHalfSize,因此当您使用i时,firstHalf将在operator[]范围内 - 在第二个向量的情况下,i并不意味着同样的事情。

答案 2 :(得分:0)

填充vector正在运作。只是您的调试输出不正确。从secondHalf输出值时,您需要使用0中的索引,而不是firstHalfSize中的索引。

如果您利用带有一对迭代器的std::vector range constructor,您可以更简单地编写代码。数组指针可以视为迭代器:

void print(const std::vector<int>& data){ 
  for(int value : data)
    std::cout << value << " ";
  std::cout << "\n";
}

void split(int *dataIN, int dataSize){
    auto firstHalfSize = (dataSize + 1) / 2;
    std::vector<int> firstHalf(dataIN, dataIN + firstHalfSize); 
    std::vector<int> secondHalf(dataIN + firstHalfSize, dataIN + dataSize);

    std::cout << "firstHalf: ";
    print(firstHalf);
    std::cout << "seconHalf: ";      
    print(secondHalf);
}

Live demo