【问题标题】:C++: Make an array from main() available in another funtionC ++:使main()中的数组在另一个函数中可用
【发布时间】:2015-05-12 08:16:39
【问题描述】:

我正在尝试创建一个 C++ 程序,该程序存储许多与数值相关联的名称,并且可以在输入名称时更改数值。我的问题是:如果我在主函数中创建一个数组,可以从另一个函数访问它吗?如果是这样,应该怎么做?

附加代码(部分)

#include <iostream>
#include <fstream> //required as input\output is from\to file
#include <string>

using namespace std;

int name_checker (string input);

int main()
{
int cases;
cin >> cases;
string names[cases]; //this is the array.
int i=0;
while (i<cases)
{
    cin >> names[i];
    i++;
}
}

int name_checker (string input);
{
            //i want the data stored in above array to be availible here. possible?
}

【问题讨论】:

  • 可以将数组作为参数传递...
  • 您当然最好使用std::vector&lt;std::string&gt; names(cases);。并将您的函数签名更改为int name_checker (const std::vector&lt;std::string&gt;&amp; input)(请注意,函数定义没有分号!)。
  • @πάνταῥεῖ:谢谢。分号是一个错字。

标签: c++ arrays main


【解决方案1】:

是的,可能。将数组作为参数传递给函数。

把函数改成-

int name_checker (string input[]);

并将数组传递给函数-

name_checker(names);

注意:更改函数中的值也会影响原始值。

【讨论】:

  • 传递std::vector 更简单、更安全。传递数组时,还必须传递数组的容量。
  • 是的,同意,矢量更好,以节省内存。
【解决方案2】:

您应该考虑使用一个类。
因此,您可以使数组成为一个字段(正如 πάντα ῥεῖ 建议的那样,您应该考虑使用一个 vector )并 name_check 一个成员函数。

【讨论】:

  • 可能是因为你的建议和原来的程序完全不一样。
猜你喜欢
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 2021-08-19
  • 2021-07-15
  • 1970-01-01
  • 2013-08-09
  • 2014-03-24
  • 1970-01-01
相关资源
最近更新 更多