【问题标题】:Is there a way to make all input array elements to be passed to a function?有没有办法让所有输入数组元素都传递给函数?
【发布时间】:2022-01-04 09:09:53
【问题描述】:
cout << "Enter number:" << endl;
// number has to be stored in array
cin >> input[number];
// function has to work with every element and element that is 2 positions further
gcd(input[0], input[0+2]);

【问题讨论】:

  • C 方式:将指向第一个元素的指针与数组中的元素数一起传递。 C++ 方式:使用std::vector&lt;int&gt; 并将const 引用传递给向量。
  • 或同时适用于CC++ 的STL 方式,传递一个指向第一个元素的指针和一个指向最后一个元素之后的指针:gcd(input, input + 2);
  • gcd的签名是什么?
  • gcd(查找除数的函数名称)
  • 旁白:您的 cmets 与您的代码不匹配。 number 被用作索引,它不是存储在 input 中任何位置的值

标签: c++ arrays function


【解决方案1】:

在我看来,最惯用的方法是使用向量。喜欢:

std::vector<int> input;

std::cout << "Enter the size of the array: " << std::flush;
std::size_t count;
std::cin >> count >> std::ws;
input.reserve(count);

while (count--) {
  std::cout << "Enter a number: " << std::flush;
  int number;
  std::cin >> number >> std::ws;
  input.push_back(number);
}
    
// You can pass the whole vector to a function:
//   int gcd(std::vector<int> v);
// Or just a reference to it:
//   int gcd(std::vector<int>& v);
// And if you don't want to change the vector from inside the function, a const reference:
//   int gcd(std::vector<int> const& v);

Live Example

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2020-04-15
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2020-02-20
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多