c++ - 通过引用函数传递数组
问题描述
我需要帮助通过引用将数组传递给函数。数组是预先创建的,并被传递给函数,但通过函数后数组的值不是我想要的 - 它保持不变。代码如下所示。函数是取一个数组,一个位置 p 和一个值 val。假定数组按升序排序直到位置 p 并且值 val 必须放置使得数组按升序排序直到位置 p+1。
#include <iostream>
using namespace std;
// Function that takes an array a, a position,
// and a float value val to insert.
// a must already be sorted in acsending order
// up to p. val is then inserted such that
// the a is sorted up to p+1.
// p = 0 means position a[0].
void insert(double (&a)[], int aSize, int p, double val)
{
try {
// Throw error if p > size of array
if(p > aSize || p < 0) {
throw logic_error("Position is greater than size of array or less than zero.");
}
int newSize = aSize + 1;
double* vTemp = new double[newSize]; // create new bigger array
for(int i = 0; i <= p; i++) {
if(val >= a[i]) {
vTemp[i] = a[i];
} else {
vTemp[i] = val;
for(int j = i + 1; j < newSize; j++) {
vTemp[j] = a[j - 1];
}
break;
}
}
cout << "Size of vTemp = " << newSize << endl;
for (int k = 0; k < newSize; k++){
cout << "vTemp[" << k << "] = " << vTemp[k] << endl;
}
a = vTemp;
delete[] vTemp;
} catch(const logic_error& e) {
cout << "Error in input: " << e.what() << endl;
}
}
int main()
{
// Declare variables
double myArray[] = { 1, 2, 4, 8, 16, 20, 50, 30, 153 }; // sample array to test function
int p = 5; // position
double val = 7.2; // value to insert
int arraySize = sizeof(myArray) / sizeof(myArray[0]); // no. of elements in array
int newSize = 0; // size of expanded matrix
// Insert val
insert(myArray, arraySize, p, val);
cout << "Size of original array: " << arraySize << endl;
// Display new expanded matrix
newSize = sizeof(myArray) / sizeof(myArray[0]); // size of expanded matrix
cout << "Size of expanded array: " << newSize << endl << endl;
for(int i = 0; i < newSize; i++) {
cout << myArray[i] << " ";
}
cout << endl;
// Return success
return 0;
}
解决方案
不要使用原始数组。您正在寻找的课程被称为std::vector
(参考)。
只需创建一个向量而不是数组并通过引用传递它,您就可以获得所需的内容。
推荐阅读
- mysql - SO的投票数之类的东西应该如何存储在数据库中?
- matlab - 创建 .p 文件时如何保留帮助文本?
- .net - 成功登录 AzureAD 后出现 MissingMethodException
- python - 在 Tensorflow 中使用 Rmsprop 进行线性回归
- html - 我的导航栏链接没有按照我想要的方式浮动
- sql - 创建聚合 SQL 报告,其中列基于表列表
- lwip - 由于“MEM PBUF_POOL”达到最大值,LWIP TCP 客户端传输停止
- elasticsearch - 如何在 Grafana Gauge 中显示最后一个值
- android - 如何在 Android 首选项中正确接收和存储本地目录/路径?
- django - 姜戈。用户从网页保存模型时填充用户名或 ID