Another 'pointer to pointer' question
I want to expand on another post I had asked earlier, but change
something and see if it is still OK.
Old post summary:
Q-
I need to have an array of pointers to something. I do not know how
many I will have until runtime. How do you allocate? It needs to be in
the form: type **, because the API I am using asks for it in that
way.
A-
Use std::vector
#include <vector>
void some_function(int**);
class A
{
A()
{
// append with push_back
for (int i = 1; i < 4; ++i) {
m_integers.push_back( new int(i) );
}
// pass to C API
int** pint = &m_integers[0];
some_function(pint);
}
// add copy, assignment and destructor
// remember to delete the ints
private:
std::vector<int*> m_integers;
};
That worked great. Now I am going to end up having alot of these
buffers, but only need to pass a few to the API. Which ones will be
dynamic. I want to see if I involve a map of pointers, if the code is
still going to be OK. I know a map is not contiguous like a vector,
but I don't know if it matters when I just store pointers in the map?
Lemme see if I can code this example:
#include <vector>
// In thier C API, the buffer is some other thing they do not describe
// I just get a pointer to it. I just made this a vector for the
example
typedef std::vector<int> Buffer;
void some_function(Buffer **);
class A
{
A()
{
// Create the master collection of buffers
Buffer * buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Numbers", buffer);
buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Indices", buffer);
buffer = new Buffer();
for (int i = 0; i < 3; ++i)
{
buffer->push_back(i);
}
m_master.push_back("Kilometers", buffer);
// Pass only the needed buffers to the C API
m_current.push_back( m_master["Numbers"] );
m_current.push_back( m_master["Indices"] );
Buffer ** pBuffers = &(m_current[0]);
some_function(pBuffers);
}
// add copy, assignment and destructor
// remember to delete allocated memory
private:
typedef std::map<std::string, Buffer *> MasterBufferCollection;
MasterBufferCollection m_master;
typedef std::vector<Buffer *> CurrentBuffers;
CurrentBuffers m_current;
};