如何在方法中更改受方法影响的变量/java put方法的c++替代方案

How to change the variable, affected by a method, in the method?/c++ alternative to java put method

本文关键字:方法 java put 方案 变量 c++ 影响      更新时间:2023-10-16

我希望该方法通过在代码中包含变量来更改变量。与java中的put方法类似,我希望通过将索引设置为一个数字,然后用另一个数字重写该索引处的数字来影响变量。

例如:

#include <iostream>
#include <string>
using namespace std;
string put(int pos, float f)
{
  a = f[pos];
  //pos - The index at which the float will be written
  //f - The float value to be written 
}
int main ()
{
  int x = 6;
  int y = 2;
  int z = 3;
  float a[100];
  a.put(10, y)
}

唯一的问题是,put方法只更改变量a,而我希望它更改指向它的任何变量。因此,如果有一个像b这样的变量,并且在代码中出现为b.put(23, z),它会用数字3重写索引23处的任何内容。

似乎C++中的指针可以实现您所尝试的。

void put(float* a, int pos, float change){
    a[pos]=change;
}

当然,您需要小心访问超过数组大小的内存位置,但此put函数适用于任何数组。然而,这就引出了一个问题,即您到底想做什么,因为直接更改值会更容易阅读。我能想象你在Java中引用的唯一一个"put"方法是HashMaps,而C++的等效方法是unordered_map。更多信息可以在这里找到。它有一个插入函数,相当于Java put。

通过阅读上面的评论,使用指向变量的指针而不是变量本身将实现您想要的目标。

定义类来创建此类函数。

#include <iostream>
#include <string>
class hoge {
private: // only for readability
  float a[100];
public:
  void put(int pos, float f)
  {
    if (pos >= 0 && pos < (int)(sizeof(a) / sizeof(a[0]))) a[pos] = f;
    //pos - The index at which the float will be written
    //f - The float value to be written 
  }
};
int main ()
{
  int x = 6;
  int y = 2;
  int z = 3;
  hoge a;
  a.put(10, y);
}