在c ++中创建一个类实例的向量

时间:2021-12-08 21:21:19

i created a class its name is Student as follows:

我创建了一个类,其名称为Student,如下所示:

class Student
{
 private:
     unsigned int id;                                // the id of the student 
public:   
    unsigned int get_id(){return id;};   
    void set_id(unsigned int value) {id = value;};
    Student(unsigned int init_val) {id = init_val;};   // constructor
    ~Student() {};                                     // destructor
};

then after i wanted to have a container ( say a vector ) its elements are instances of class Student, but i found myself not able to understand this situation , here is my issue:

然后在我想要一个容器(比如一个向量)后,它的元素是类Student的实例,但我发现自己无法理解这种情况,这是我的问题:

first i run this code:

首先我运行此代码:

#include<iostream>
#include<vector>
using namespace std;

const unsigned int N = 5;

Student ver_list[2] = {7, 9};


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver_list[1].get_id() << endl;

return 0;
}

everything is fine and the output is :

一切都很好,输出是:

Hello, This is a code to learn classes
9

now when i try these options:

现在当我尝试这些选项时:

option #1:

#include<iostream>
#include<vector>
using namespace std;

const unsigned int N = 5;

vector <Student> ver[N];             // Create vector with N elements
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i); 


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver[1].get_id() << endl;

return 0;
}

i got this output "error" :

我得到这个输出“错误”:

test.cpp:26:3: error: expected unqualified-id before 'for'
   for(unsigned int i = 0; i < N; ++i )
   ^
test.cpp:26:27: error: 'i' does not name a type
   for(unsigned int i = 0; i < N; ++i )
                           ^
test.cpp:26:34: error: expected unqualified-id before '++' token
   for(unsigned int i = 0; i < N; ++i )
                                  ^
test.cpp: In function 'int main()':
test.cpp:43:15: error: 'class std::vector<Student>' has no member named 'get_id'

 cout<< ver[1].get_id() << endl;
               ^

option #2:

#include<iostream>
#include<vector>
using namespace std;

const unsigned int N = 5;

Student ver[N];                       // Create one dimensional array with N elements
for(unsigned int i = 0; i < N; ++i )
   ver[i].set_id(i); 


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver[1].get_id() << endl;

return 0;
}

the output "error" was :

输出“错误”是:

test.cpp:30:14: error: no matching function for call to 'Student::Student()'
Student ver[5];
             ^
test.cpp:30:14: note: candidates are:
test.cpp:14:2: note: Student::Student(unsigned int)
  Student(unsigned int init_val) {id = init_val;};   // constructor
  ^
test.cpp:14:2: note:   candidate expects 1 argument, 0 provided
test.cpp:7:7: note: Student::Student(const Student&)
 class Student
       ^
test.cpp:7:7: note:   candidate expects 1 argument, 0 provided
test.cpp:31:1: error: expected unqualified-id before 'for'
 for(unsigned int i = 0; i < N; ++i )
 ^
test.cpp:31:25: error: 'i' does not name a type
 for(unsigned int i = 0; i < N; ++i )
                         ^
test.cpp:31:32: error: expected unqualified-id before '++' token
 for(unsigned int i = 0; i < N; ++i )
                                ^

In the first try everything was looking ok , but when i tried the two next options , i received errors , i wish that i can understand what wrong i am doing.

在第一次尝试时,一切都看起来不错,但是当我尝试下两个选项时,我收到错误,我希望我能理解我在做什么错。

Thanks.

4 个解决方案

#1


11  

This:

vector <Student> ver[N];

Creates an array of N elements. Each element is vector<Student>. This is not you want. You were probably trying to create a vector of N elements. The syntax for this is:

创建一个包含N个元素的数组。每个元素都是vector 。这不是你想要的。您可能正在尝试创建N个元素的向量。这个语法是:

vector <Student> ver(N);

But you can't use this because your class does not have a default constructor. So your next alternative is to initializae all the objects with the same element.

但是你不能使用它,因为你的类没有默认的构造函数。因此,您的下一个选择是初始化具有相同元素的所有对象。

vector <Student> ver(N, Student(0));

You also tried to create an array of students like this:

你还尝试创建一个像这样的学生阵列:

Student ver[N];

This will not work. Because it tries to initialize every element in the array with the default constructor. But your class does not have a default constructor. So this will not work. But this is why your original code did work:

这不行。因为它尝试使用默认构造函数初始化数组中的每个元素。但是你的类没有默认的构造函数。所以这不行。但这就是你的原始代码确实有效的原因:

Student ver_list[2] = {7, 9};  // Here you are using the constructor for your object.
                               // It uses the normal constructor you provided not the default one.

The other issues is that you can not run code outside a function(method).
So this will not work:

其他问题是您无法在函数(方法)之外运行代码。所以这不起作用:

for(unsigned int i = 0; i < N; ++i )
    ver[i].set_id(i); 

In C++11 you can initialize a vector the same way as an array:

在C ++ 11中,您可以像数组一样初始化向量:

vector<Student>  ver = { 0, 1, 2, 3, 4, 5};

If you don't have C++11 or initialization is more complex. Then you need to write a wrapper.

如果你没有C ++ 11或初始化更复杂。然后你需要写一个包装器。

class VecWrapper
{
     public:
         std::vector<Student>   ver;
         VecWrapper()
         {
            ver.reserve(N);
            for(unsigned int i = 0; i < N; ++i )
                ver.push_back(Student(i));
         }
 };

Now You can place this in global scope and it will auto init.

现在您可以将它放在全局范围内,它将自动初始化。

 VecWrapper   myData;  // myData.vec  initializaed before main entered.

 int main()
 {}

Full solution:

Option 2:

#include<iostream>
#include<vector>
using namespace std;

const unsigned int N = 5;

// The following is not correct
// This creates an arrya of `N` elements each element is `vector <Student>`
//
// vector <Student> ver[N];             // Create vector with N elements
// 

// The following lines are not allowed.
// All code has to be inside a function.
//
// for(unsigned int i = 0; i < N; ++i )
// ver[i].set_id(i); 


// What you want is:
//    I use the following because it is unclear if you have C++11 or not.  
class VecWrapper
{
   public:
     std::vector<Student>   vec;
     VecWrapper()
     {
        vec.reserve(N);
        for(unsigned int i = 0; i < N; ++i )
            vec.push_back(Student(i));
     }
};
VecWrapper   myData;  // myData.vec 
int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< myData.vec[1].get_id() << endl;

return 0;
}

#2


2  

The main problem is you are trying to execute a for loop at global scope. It is acceptable to define and initialize variables outside of a function, but using a for loop or assignment operator is not. Put the for loop into main() (and I would recommend you also put N and the vector/student array into main() and everything should work.
Additionally, the compiler is complaining because when you declare Student array[5]; or vector<Student> ver[N]; it is looking for a default constructor for Student called Student(), which just sets default values for a class. You need to provide this inside the Student class; set the id to some value that can never be an actual student ID, something like -1.

主要问题是你试图在全局范围内执行for循环。定义和初始化函数外部的变量是可以接受的,但是使用for循环或赋值运算符则不行。把for循环放到main()中(我建议你也把N和vector / student数组放到main()中,一切都应该有效。另外,编译器抱怨因为当你声明Student array [5];或者vector ver [N];它正在寻找一个名为Student()的默认构造函数,它只为类设置默认值。你需要在Student类中提供它;将id设置为一个永远不能的值是一个真正的学生证,如-1。

#3


1  

Option #1:

You should replace vector <Student> ver[N] with vector<Student> ver(N)

你应该用vector ver(N)替换vector ver [N]

The std::vector is a class, that represents the vector by himself, you shouldn't create an array of vectors, you should just pass N(vector size) to it's constructor. Check this link

std :: vector是一个类,它自己表示向量,你不应该创建一个向量数组,你应该只将N(向量大小)传递给它的构造函数。检查此链接

Option #2:

Student ver[N];

is incorrect, since the Default Constructor Student() is invoked N times, but you haven't implement it. So you have to use array initilizer Student ver[5] = {1, 2, 3, 4, 5} or implement the default constructor explicitly.

是不正确的,因为默认构造函数Student()被调用N次,但您还没有实现它。所以你必须使用数组启动器Student ver [5] = {1,2,3,4,5}或显式实现默认构造函数。

And of course - the "for" loop has to be used inside function body.

当然 - 必须在函数体内使用“for”循环。

#4


0  

This is actually not linked at all with vectors. You just need to move your "for" statement into your main

实际上,它与矢量完全没有联系。您只需将“for”语句移动到主要语句中即可

#1


11  

This:

vector <Student> ver[N];

Creates an array of N elements. Each element is vector<Student>. This is not you want. You were probably trying to create a vector of N elements. The syntax for this is:

创建一个包含N个元素的数组。每个元素都是vector 。这不是你想要的。您可能正在尝试创建N个元素的向量。这个语法是:

vector <Student> ver(N);

But you can't use this because your class does not have a default constructor. So your next alternative is to initializae all the objects with the same element.

但是你不能使用它,因为你的类没有默认的构造函数。因此,您的下一个选择是初始化具有相同元素的所有对象。

vector <Student> ver(N, Student(0));

You also tried to create an array of students like this:

你还尝试创建一个像这样的学生阵列:

Student ver[N];

This will not work. Because it tries to initialize every element in the array with the default constructor. But your class does not have a default constructor. So this will not work. But this is why your original code did work:

这不行。因为它尝试使用默认构造函数初始化数组中的每个元素。但是你的类没有默认的构造函数。所以这不行。但这就是你的原始代码确实有效的原因:

Student ver_list[2] = {7, 9};  // Here you are using the constructor for your object.
                               // It uses the normal constructor you provided not the default one.

The other issues is that you can not run code outside a function(method).
So this will not work:

其他问题是您无法在函数(方法)之外运行代码。所以这不起作用:

for(unsigned int i = 0; i < N; ++i )
    ver[i].set_id(i); 

In C++11 you can initialize a vector the same way as an array:

在C ++ 11中,您可以像数组一样初始化向量:

vector<Student>  ver = { 0, 1, 2, 3, 4, 5};

If you don't have C++11 or initialization is more complex. Then you need to write a wrapper.

如果你没有C ++ 11或初始化更复杂。然后你需要写一个包装器。

class VecWrapper
{
     public:
         std::vector<Student>   ver;
         VecWrapper()
         {
            ver.reserve(N);
            for(unsigned int i = 0; i < N; ++i )
                ver.push_back(Student(i));
         }
 };

Now You can place this in global scope and it will auto init.

现在您可以将它放在全局范围内,它将自动初始化。

 VecWrapper   myData;  // myData.vec  initializaed before main entered.

 int main()
 {}

Full solution:

Option 2:

#include<iostream>
#include<vector>
using namespace std;

const unsigned int N = 5;

// The following is not correct
// This creates an arrya of `N` elements each element is `vector <Student>`
//
// vector <Student> ver[N];             // Create vector with N elements
// 

// The following lines are not allowed.
// All code has to be inside a function.
//
// for(unsigned int i = 0; i < N; ++i )
// ver[i].set_id(i); 


// What you want is:
//    I use the following because it is unclear if you have C++11 or not.  
class VecWrapper
{
   public:
     std::vector<Student>   vec;
     VecWrapper()
     {
        vec.reserve(N);
        for(unsigned int i = 0; i < N; ++i )
            vec.push_back(Student(i));
     }
};
VecWrapper   myData;  // myData.vec 
int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< myData.vec[1].get_id() << endl;

return 0;
}

#2


2  

The main problem is you are trying to execute a for loop at global scope. It is acceptable to define and initialize variables outside of a function, but using a for loop or assignment operator is not. Put the for loop into main() (and I would recommend you also put N and the vector/student array into main() and everything should work.
Additionally, the compiler is complaining because when you declare Student array[5]; or vector<Student> ver[N]; it is looking for a default constructor for Student called Student(), which just sets default values for a class. You need to provide this inside the Student class; set the id to some value that can never be an actual student ID, something like -1.

主要问题是你试图在全局范围内执行for循环。定义和初始化函数外部的变量是可以接受的,但是使用for循环或赋值运算符则不行。把for循环放到main()中(我建议你也把N和vector / student数组放到main()中,一切都应该有效。另外,编译器抱怨因为当你声明Student array [5];或者vector ver [N];它正在寻找一个名为Student()的默认构造函数,它只为类设置默认值。你需要在Student类中提供它;将id设置为一个永远不能的值是一个真正的学生证,如-1。

#3


1  

Option #1:

You should replace vector <Student> ver[N] with vector<Student> ver(N)

你应该用vector ver(N)替换vector ver [N]

The std::vector is a class, that represents the vector by himself, you shouldn't create an array of vectors, you should just pass N(vector size) to it's constructor. Check this link

std :: vector是一个类,它自己表示向量,你不应该创建一个向量数组,你应该只将N(向量大小)传递给它的构造函数。检查此链接

Option #2:

Student ver[N];

is incorrect, since the Default Constructor Student() is invoked N times, but you haven't implement it. So you have to use array initilizer Student ver[5] = {1, 2, 3, 4, 5} or implement the default constructor explicitly.

是不正确的,因为默认构造函数Student()被调用N次,但您还没有实现它。所以你必须使用数组启动器Student ver [5] = {1,2,3,4,5}或显式实现默认构造函数。

And of course - the "for" loop has to be used inside function body.

当然 - 必须在函数体内使用“for”循环。

#4


0  

This is actually not linked at all with vectors. You just need to move your "for" statement into your main

实际上,它与矢量完全没有联系。您只需将“for”语句移动到主要语句中即可