【问题标题】:C++: Passing string arrays to function WITHOUT USING VECTORSC++:在不使用向量的情况下将字符串数组传递给函数
【发布时间】:2014-09-29 08:12:07
【问题描述】:

所以对于我的课堂作业,我必须完成这个成绩册计划。我正在努力的部分是弄清楚如何将字符串数组从一个函数传递到另一个函数,以便后一个函数可以对存储在字符串数组中的数据执行计算。好吧,进一步缩小到更大的图景,字符串数组(用于学生姓名)与双精度数组(用于分数)平行,接收数组的函数必须找到最高和最低,计算均值并打印输出到屏幕和文件。我得到了最后一点,但我无法弄清楚在不使用向量的情况下将数组引用到函数的正确语法!

重要提示:如果您不知何故错过了它,我们不允许在此作业中使用向量。

所以大致的大纲是:

//blahblahblah, #includes and other starting things

int myFunc(//prototype-what the heck goes here?)    

int main()
{
    //arrays declared
    string names[MAX_NUM];
    double scores[MAX_NUM];
    //...other stuff main does, including calling myFunc...
}

int myFunc( //header-what the heck goes here?)
{
    //Code here to find highest, lowest, and mean scores from data in scores[]
}

显然,每个都表明“这里到底发生了什么?”位置将与另一个中的内容有关。但我不知道如何让它全部工作,我能找到的每一个答案都只是说使用向量。我们还没有涉及,因此无法使用...请帮助?

【问题讨论】:

  • 向量有什么问题?
  • 到目前为止你尝试了什么?你的教科书是怎么说的?您的 C++ 编程参考/书籍/资源对将数组传递给函数有何看法?
  • 谷歌“指针和数组的等价性”。
  • 给你们的下一个问题是:如何在不尖叫的情况下提出问题。请继续关注。
  • 使用 std::array (C++11) 的语法比 C-array 更简洁。

标签: c++ function pass-by-reference arrays


【解决方案1】:
template<std::size_t size>
int myFunc(std::string (&names)[size]);

int myFunc(std::string *names, std::size_t numberOfNames);

int myFunc(std::string *names); //implicitly assume names points to MAX_NUM strings

【讨论】:

    【解决方案2】:
    //blahblahblah, #includes and other starting things
    
    int myFunc(string names[], double scores[], int elementCount);
    
    int main()
    {
       //arrays declared
       string names[MAX_NUM];
       double scores[MAX_NUM];
       //...other stuff main does, including calling myFunc...
       myFunc(names, scores, elementCount);
    }
    
    int myFunc(string names[], double scores[], int elementCount)
    {
       //Code here to find highest, lowest, and mean scores from data in scores[]
    }
    

    【讨论】:

    • 您的解决方案必须假设尺寸:-/
    • 很容易修改
    【解决方案3】:

    我可能会使用

    myFunc(std::string* names, double* scores, std::size_t n_students) { /*...*/ }
    

    或者,如果使用无向量策略过于精确,您可以使用 std::list&lt;std::pair&lt;std::string, double&gt;&gt; 或类似的东西...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2010-11-19
      • 2013-04-08
      • 2013-06-27
      • 2011-10-31
      • 2018-03-26
      • 1970-01-01
      相关资源
      最近更新 更多