I am receiving an error: "Expression must have class type".
I am supposed to "Create a table which is a vector of 'Essay', which is dynamically created with the 'new' operator".
However, when reading online, I guess it's not good to use the 'new' operator with vector?
HEADER FILE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <vector>
#include <string>
struct Essay {
std::string word;
std::string paragraph;
Entry () { word = "---"; }
};
class AB {
private:
std::vector<Essay>* table;
int table_size;
public:
AB(int size);
~AB();
};
MAIN FILE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
AB::AB(int s = 10)
{
//Essay *table = new Essay[s] //This will work but I
//believe it is incorrect
table.reserve(s); //ERROR: Expression must have class type
table_size = 0;
}
AB::~AB()
{
}
table is a pointer. To be able to call the reserve function on the vector that the pointer points to you have to first dereference the pointer.
(*table).reserve(s);
Or you can use the shorter "arrow" syntax.
table->reserve(s);
If you don't have a very good reason for using pointers and new you should stay away from them because they complicate the code and it's easy to make mistakes.
I would guess that not the vector should be created with new, but an object of the type AB. Or Essay. Then you would need a vector of pointer.
And yes: creating a vector dynamically is not usefull since itself manages the data dynamically.
By the way: you don't need table_size since vector has a size() member.
'table' is a hash table. The 'word' string is actually a 'key' which is always in the form of.. "letter-letter-int" The 'table' is a container of type vector<Essay> and is used to store entries.
In the constructor, the hash table 'table' which is a vector of 'Essay' is supposed to be created dynamically (with the new operator) for a given size 's'.