Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a vector of instances of a class in c++

Tags:

c++

class

i created a class its name is Student as follows:

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:

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.

like image 776
mazlor Avatar asked Oct 29 '13 12:10

mazlor


People also ask

How do you create a class vector?

Program to create Custom Vector Class in C++ int push_back(data): adds an element(of any data_type) to the end of array and also returns the number of elements in that vector. data_type pop_back(): removes an element from the end of array, also returns the popped element.

Can you have a vector of classes in C++?

In C++11 you can initialize a vector the same way as an array: 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.

What is a vector in C __?

In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library.


1 Answers

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:

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:

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.

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;
}
like image 124
Martin York Avatar answered Oct 15 '22 07:10

Martin York