Looking for a simple wrapper for a dynamic array of string pointers in C++
I need a simple class to wrap a c style array of pointer strings, namely char **
struct CstrVector
{
CstrVector(){}
char *convertToC(const std::string & str)
{
char *c = new char[str.size()+1];
std::strcpy(c, str.c_str());
return c;
}
void add( const char* c)
{
//??
}
void add(const std::string& str )
{
data.push_back(convertToC(str));
}
void add(const std::string& s, unsigned int pos )
{
if( pos < data.size())
{
data[pos] = convertToC(s);
}
}
~CstrVector()
{
for ( size_t i = 0 ; i < data.size() ; i++ )
{
delete [] data[i];
}
}
char ** vdata;
std::vector<char*> data; // I want to replace this with char ** vdata
};
Why not use
std::vector<char*>
I don't see a benefit it since I still have to allocate and free the memory outside the container ( std::vector ) anyway
Why not use std::vector<std:string>
because I wan开发者_如何学运维t to be able to easily pass the array to a C function that will manipulate / change it contents.You should be using
std::vector<std:string>
If you want to pass char
string to c functions you can simply do so using string::c_str
You could still use the std::vector<char *>
. The vector
guarantees to store its contents in a consecutive manner, more precisely in an array. If you want to pass the char **
array to a C function you just have to pass the address of the first element in the vector:
void c_function(char ** data);
std::vector<char *> myvec;
...
c_function(&myvec[0]);
Notes:
- You still have to do the memory management for the single
char*
s - this only works for
std::vector<char*>
and not forstd::vector<std::string>
!
Would Boost ptr_vector work for you?
精彩评论