【问题标题】:Passing array of strings to a function将字符串数组传递给函数
【发布时间】:2016-12-08 15:27:43
【问题描述】:

我正在尝试创建一个程序,该程序使用类、数组和函数来显示有关两个学生的信息(姓名、id#、注册的课程)。我正在努力的部分是将数组传递给函数。我该怎么做?

#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

class Student // Student class declaration.
{
private:
  string name;
  int id;
  string classes;
  int arraySize;

public:
  void setName(string n)
  {
    name = n;
  }
  void setId(int i)
  {
    id = i;
  }
  void setClasses(string c, int num)
  {
    classes = c;
    arraySize = num;
  }
  string getName()
  {
    return name;
  }
  int getId()
  {
    return id;
  }
  void getClasses()
  {
    for (int counter=0; counter <arraySize; counter++) {

      cout << classes[counter] << endl;
    }

  }

};

int main()
{
  //Student 1
  string s1Name = "John Doe";
  int s1Id = 51090210;
  int const NUMCLASSES1 = 3;
  string s1Classes[NUMCLASSES1] = {"C++","Intro to Theatre","Stagecraft"};
  //Student 2
  string s2Name = "Rick Harambe Sanchez";
  int s2Id = 666123420;
  int const NUMCLASSES2 = 2;
  string s2Classes[NUMCLASSES2] = {"Intro to Rocket Science","Intermediate Acting"};
  //

  Student info;

  info.setName(s1Name);
  info.setId(s1Id);
  //info.setClasses(s1Classes, NUMCLASSES1);
  cout << "Here is Student #1's information:\n";
  cout << "Name: " << info.getName() << endl;
  cout << "ID: " << info.getId() << endl;
  //cout << "Classes: " << info.getClasses() << endl;


  info.setName(s2Name);
  info.setId(s2Id);
  // info.setClasses(s2Classes, NUMCLASSES1);
  cout << "\n\nHere is student #2's information:\n";
  cout << "Name: " << info.getName() << endl;
  cout << "ID: " << info.getId() << endl;
  //cout << "Classes: " << info.getClasses() << endl;



  return 0;
}

【问题讨论】:

  • 作为初学者,比起原始数组,更喜欢std:.vector。传递std::vector 与传递intstd::string 相同。
  • 你在这段代码中的什么地方试图将数组传递给函数?你可以传递一个指针,但你也应该传递一个长度。您可以改用std::arrayvector,就像其他许多人建议的那样。

标签: c++ arrays function visual-c++ c++14


【解决方案1】:

在 Student 类的私有变量中,您存储了一个字符串: String classes; 您应该在哪里存储一个字符串数组,例如: String classes[MAX_NUM_CLASSES];

然后在 set classes 函数中,传入一个字符串数组作为第一个参数,所以应该是:

void setClasses(string[] c, int num)

{

classes = c; //not sure if simply setting them equal will work, rather copy entire array using a for loop

 arraySize = num;

}

这应该为您指明正确的方向

另外,使用std::vector而不是string[],会更容易。

【讨论】:

    【解决方案2】:

    在 C++ 中传递可变长度列表的常用方法是使用std::vectorvector 是单个对象,您可以轻松地将其传递给函数,复制(或引用)其内容。如果您熟悉 Java,则基本上是 ArrayList。这是一个例子:

    #include <vector>
    #include <string>
    using namespace std;
    
    class foo {
    private:
      vector<string> myStrings;
    
    public:
      void setMyStrings(vector<string> vec) {
        myStrings = vec;
      }
    }
    
    //...
    
    foo myObj;
    vector<string> list = {"foo","bar","baz"};
    myObj.setMyStrings(list);
    

    如果不想使用标准库,您可以传递 C 样式的数组。这涉及将指针传递给数组的第一个元素,以及数组的长度。示例:

    void processStrings(string* arr, int len) {
      for (int i = 0; i < len; i++) {
        string str = arr[i];
        //...
      }
    }
    
    string array[] = {"foo","bar","baz"};
    processStrings(array, 3); // you could also replace 3 with sizeof(array)
    

    像这样传递原始数组,特别是如果您想将数组复制到对象中,可能会很痛苦。 C 和 C++ 中的原始数组 只是指向列表第一个元素的指针。 与 Java 和 JavaScript 等语言不同,它们不跟踪其长度,并且您不能只将一个数组分配给另一个数组。 std::vector 封装了“事物列表”的概念,通常更直观地用于该目的。

    人生教训:使用 std::vector。

    编辑:有关使用构造函数更干净地初始化对象的示例,请参阅@nathanesau 的答案。 (但不要复制粘贴,自己写!这样学起来会快很多。)

    【讨论】:

      【解决方案3】:

      使用std::vector。另外,不要添加不需要的功能。下面是一个使用std::vector的例子

      #include <string>
      #include <iostream>
      #include <vector>
      
      using std::string;
      using std::vector;
      
      class Student // Student class declaration.
      {
      private:
      
          vector<string> classes;
          string name;
          int id;
      
      public:
      
          Student (const vector<string> &classesUse, string nameUse, int idUse) :
              classes (classesUse),
              name    (nameUse),
              id      (idUse)
          {
          }
      
          void print ()
          {
              std::cout << "Name:    " << name << std::endl;
              std::cout << "Id:      " << id << std::endl;
              std::cout << "Classes: ";
      
              for (int i = 0; i < classes.size (); i++)
              {
                  if (i < classes.size () - 1)
                  {
                      std::cout << classes[i] << ", ";
                  }
                  else
                  {
                      std::cout << classes[i] << std::endl;
                  }
              }
      
              std::cout << std::endl;
          }
      };
      
      int main()
      {
          Student John ({"C++","Intro to Theatre","Stagecraft"},
                        "John",
                        51090210);
      
          John.print ();
      
          Student Rick ({"Intro to Rocket Science","Intermediate Acting"},
                        "Rick",
                        666123420);
      
          Rick.print ();
      
          return 0;
      }
      
      
      Name:    John
      Id:      51090210
      Classes: C++, Intro to Theatre, Stagecraft
      
      Name:    Rick
      Id:      666123420
      Classes: Intro to Rocket Science, Intermediate Acting
      

      【讨论】:

        【解决方案4】:

        您可以像这样将any_data_type 的数组传递给function

        void foo(data_type arr[]);
        
        foo(arr); // If you just want to use the value of array 
        foo(&arr); // If you want to alter the value of array.
        

        【讨论】:

          猜你喜欢
          • 2015-09-09
          • 2013-06-27
          • 2015-05-27
          • 1970-01-01
          • 1970-01-01
          • 2014-09-06
          • 1970-01-01
          相关资源
          最近更新 更多