How to create an array of n positions, C ++

0

My question is how to declare an array without specifying the length and then instantiate it in the constructor method by specifying the quantity.

To enter the context, I leave the following example.

#ifndef GRAFO_H
#define GRAFO_H
#include <iostream>
#include <string>

using namespace std;

class grafo {
public:
    grafo();
    grafo(const grafo& orig);
    virtual ~grafo();
private:
    int num_pla;
    string nom_pla[]; // Declaración sin especificar el tamaño del array.
};

#endif /* GRAFO_H */

Now what I'm looking for is to instantiate it in the constructor of the class and specify the length as the following example in JAVA.

String b[] = new String[9];

Now, is this possible? If it is not; What other form would you recommend, to solve?

    
asked by Cookie Rabbit 16.07.2017 в 18:57
source

1 answer

1

Reply to your question

When you define an array, the size must be known at compile time, so you can not define it exactly as you are doing.

However you can define a pointer to string and later in the constructor store the memory dynamically, such that:

// En la clase
string *nom_pla;

// Mas tarde en el constructor
nom_pla = new string[x];

Remember to do a delete on the destructor to free the memory.

Recommendations

However, I recommend that you do not use an array and / or the operators new and delete, to build collections that already exist, unless you have a clear and justified use of them.

For example, you could use the class std::vector to store an array of strings .

// En la clase
std::vector<string> nom_pla;

Finally, I also advise you to delete the line:

using namespace std;

The community agrees to consider it a bad practice, due to conflicts that may arise in the future with standard and third-party libraries.

Greetings

    
answered by 16.07.2017 / 19:58
source