gpt4 book ai didi

c++ - vector push_back 的垃圾值

转载 作者:行者123 更新时间:2023-11-30 00:49:45 25 4
gpt4 key购买 nike

我正在尝试将数组的值分配给 vector 。它似乎对一个 vector 工作正常,但是当我这样做一秒钟时,我得到了垃圾值。我计算出号码,我知道它是正确的,但分配不正确。我不明白,因为它对第一个 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;
}

这是我的结果。如您所见,第一个 vector 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

最佳答案

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

您需要计算从索引 0 开始的值。例如:

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

关于c++ - vector push_back 的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27329184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com