vtleavs
vtleavs

Reputation: 69

Adding elements to a vector from an array of pointers in C++

I've been trying to use an array of pointers to point to vectors, which I have so far been able to implement, however, in trying to add an element to one of the sub-vectors, I repeatedly get an unknown error on run-time.

I have previously defined my array as so:

std::vector<std::string> *frequency_table[10000];

I then try to add an element to a specific one of the vectors. This is the line that causes the run-time error.

frequency_table[index]->push_back(value);

Any ideas?

Upvotes: 0

Views: 733

Answers (3)

kkm mistrusts SE
kkm mistrusts SE

Reputation: 5510

Your approach involves mixing vectors (and vectors are a good thing) and C-style arrays of pointers to objects (which betrays a mix-up since there are already vectors in your code).

If you want 10000 vectors of vectors of string, then just write

std::vector<std::vector<std::string> > frequency_table(10000);
. . .
frequency_table[index].push_back(value);

The first line declares a vector, each element of which is a vector<string>, allocates 10000 elements to it and initializes each element.

Upvotes: 1

vtleavs
vtleavs

Reputation: 69

Using the input from you guys, I realized that my problem was the vectors were not being initialized, so I added this loop before the loop in which I populate the vectors, and it works now:

for(int i = 0; i < 5000; ++i)
{
    frequency_table[i] = new std::vector<std::string>;
}

The final code looks like this:

for(int i = 0; i < 5000; ++i)
{
    frequency_table[i] = new std::vector<std::string>;
}

for(auto itr = frequency_map.begin(); itr != frequency_map.end(); ++itr)
{

    std::string key = itr->first;
    double value = itr->second;


    frequency_table[(int)value]->push_back(key);
}

Thanks all!

ps I halved the 10000 for testing purposes

Upvotes: 0

Krishna_Sp
Krishna_Sp

Reputation: 111

At first glance the problem looks like you haven't allocated any memory for the pointer so it has nowhere to push the value to. Though i can't be sure without the error message.

If that is the case however you would need to use new to allocate the memory

Upvotes: 3

Related Questions