gpt4 book ai didi

c++ - 合并两个数组后得到不正确的数组大小

转载 作者:太空狗 更新时间:2023-10-29 21:09:49 24 4
gpt4 key购买 nike

我获取了两个数组,然后将这两个数组合并到新创建的第三个数组中,它起作用了,但是当我输出数组的大小时,我得到的大小为“1”。我不明白为什么该数组的大小为“1”,即使其中有 5 个元素。

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
int arr1[] = { 1,2,3 };
int arr2[] = { 9,4 };
int size1 = sizeof(arr1) / sizeof(int);
int size2 = sizeof(arr2) / sizeof(int);

int *arr = new int[size1 + size2];

//merging the two arrays by transferinng the elements into the third array
for (int i = 0; i < size1; i++)
{
arr[i] = arr1[i];
}
for (int i = size1; i < (size1 + size2); i++)
{
arr[i] = arr2[i - size1];
}

//sorting the array
sort(arr, arr + (size1 + size2));
cout << endl;

//finding the size of newly merged array
int mergeSize = sizeof(arr) / sizeof(int);
cout << "The size of the array is " << mergeSize << endl; //why am I getting the size of the array as '1'
return 0;
}

最佳答案

sizeof(arr) 为您提供指针 arr 的大小,它不取决于您为其分配的元素数量。

使用 std::array 可以避免这个问题。它没有 std::vector 的开销,而且比 C 风格的数组更容易使用。

int main()
{
array<int, 3> arr1 = { 1, 2, 3 };
array<int, 2> arr2 = { 9, 4 };

array<int, arr1.size() + arr2.size()> arr;

//merging the two arrays by transferinng the elements into the third array
for (int i = 0; i < arr1.size(); i++)
{
arr[i] = arr1[i];
}
for (int i = 0; i < arr2.size(); i++)
{
arr[i + arr1.size()] = arr2[i];
}

//sorting the array
sort(arr.begin(), arr .end());
cout << endl;

//finding the size of newly merged array
int mergeSize = arr.size();
cout << "The size of the array is " << mergeSize << endl; //why am I getting the size of the array as '1'
return 0;
}

关于c++ - 合并两个数组后得到不正确的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57001255/

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