在c++中更改数组值
change array value in c++
在我的cpp程序中有一个二维数组,它在八列三行中存储双精度值。我有一个函数来确定每行的最小值。现在我想改变这个最小变量的值。我通过指针传递数组,这对我来说是一个挑战。下面是获取最小值的getMaxMin()。如有任何帮助,不胜感激。
double **getMaxMin(double **scores){
for(int i=0;i<3;i++){
double small=scores[i][0];
for(int j=1;j<8;j++){
if(small>scores[i][j]){
small=scores[i][j];
}
}
cout<<small<<endl;
}
return scores;
}
保存small
时也保存索引:
// ...
if( small > scores[i][j] )
{
small = scores[i][j];
small_i = i;
small_j = j;
}
// later
scores[small_i][small_j] = //...
我猜对于这个场景,您只需要存储列索引,因为您是逐行执行的。这是一个更通用的版本。
int smalli,smallj;
....
if(small>scores[i][j]){
small=scores[i][j];
smalli = i;
smallj = j;
}
...
scores[smalli][smallj] = newval;
这回答你的问题了吗?
double **getMaxMin(double **scores){
for(int i=0;i<3;i++){
double small=scores[i][0];
int best_j = 0; // NEW
for(int j=1;j<8;j++){
if(small>scores[i][j]){
small=scores[i][j];
best_j = j; // NEW
}
}
cout<<small<<endl;
scores[i][best_j] = 42.0f; // NEW
}
return scores;
}
我可能遗漏了一些东西,但是为什么要使用最小的地址并使用它来分配新值呢?
(注:我可能错过了一些东西,没有在愤怒中编写c++…) )
double **getMaxMin(double **scores)
{
for(int i=0;i<3;i++){
double* small = &scores[i][0];
for(int j=1;j<8;j++){
if(*small>scores[i][j]){
small=&scores[i][j];
}
}
cout<<*small<<endl;
}
*small = 100.0; // Set new value here
return scores;
}
有很多方法可以做到这一点,但最简单的方法就是保存索引。
跟踪每行的最小值:
double **getMaxMin(double **scores){
for(int i=0;i<3;i++){
double small=scores[i][0];
int small_j = 0;
for(int j=1;j<8;j++){
if(small>scores[i][j]){
small=scores[i][j];
small_j = j;
}
}
cout<<small<<endl;
// Now you can change the value of the smallest variable for that row
//small[i][small_j] = yourvalue
}
return scores;
}
跟踪整个数组中的最小值:
double **getMaxMin(double **scores){
for(int i=0;i<3;i++){
double small=scores[i][0];
int small_j = 0;
int small_i = 0;
for(int j=1;j<8;j++){
if(small>scores[i][j]){
small=scores[i][j];
small_j = j;
small_i = i;
}
}
cout<<small<<endl;
}
// Now you can do something with the smallest value in the entire array
// small[small_i][small_j] = yourvalue
return scores;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '