-4

I want the number of objects that my program creates, to be controlled by the user. What are the different ways to do this and when should I choose one approach over another?

#include<iostream>
using namespace std;

class
{
public :
   int FullName;
   int RollNumber;
   in
{
public :
   int FullName;
   int RollNumber;
   int age;
   int marks;
}
voidt age;
   int marks;
};
void main()
{
   int n;
   cout << "How many Students record you want :\t ";
   cin >>n;     
   Data Student[n];
}
Josie Thompson
  • 5,608
  • 1
  • 13
  • 24
UAhmadSoft
  • 97
  • 1
  • 9
  • you are already reading into `n` the entered value, so what exactly are you stuck with? – EdChum Sep 13 '18 at 15:20
  • 9
    You're looking for `std::vector`. – HolyBlackCat Sep 13 '18 at 15:20
  • Two basic approaches. Get a count of things to read in, then read in that many. Or read in things until you get some sort of terminator which indicates "no more items to read in". – Eljay Sep 13 '18 at 15:21

2 Answers2

0

Like said before, use std::vector.

Your example however seems to work: https://onlinegdb.com/HyHjwZddQ

  • 2
    This is called a *variable length array* (*VLA*) and is not a part of the standard C++. It is a compiler extension. `std::vector` **is** the preferred way. – Fureeish Sep 14 '18 at 00:13
  • 1
    Stuff like `Data Student[n];` isn't valid C++, because [C++ doesn't have variable length arrays](https://stackoverflow.com/q/1887097/9254539). Code like this only compiles because of a GCC non-standard extension. You should use an `std::vector` instead to make your code portable and avoid blowing out the stack. – eesiraed Sep 14 '18 at 00:18
0

If the number of items becomes fixed at the moment of creation, your best option is

std::make_unique<Data[]>(n)

But if you might need to change the group of items later (insert or remove), then

std::vector<Data>(n)
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • What is the advantage of using an array directly (on the heap) over an std::vector which also uses the heap? Both have the same memory lay out after all. If you need to insert or remove I would rather use a list. – Frederik De Ruyck Sep 14 '18 at 07:53
  • @FrederikDeRuyck: Neither suggestion is to "use an array directly". I suggested the smart pointer with fewer operations, when those are sufficient, and the smart pointer with more operations when you need them. And locality/cache efficiency means a linked list usually loses to contiguous storage even on insert and remove. – Ben Voigt Sep 14 '18 at 13:56