开发者

Looking for a simple wrapper for a dynamic array of string pointers in C++

开发者 https://www.devze.com 2023-03-31 00:02 出处:网络
I need a simple class to wrap a c style array of pointer strings, namely char ** I need minimal operations on my wrapper including adding elements( const or non const ), iterating, random access and

I need a simple class to wrap a c style array of pointer strings, namely char **

I need minimal operations on my wrapper including adding elements( const or non const ), iterating, random access and querying size. I started using a std::vector like below but I don't like it for reasons described below

This is my start

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 for std::vector<std::string>!


Would Boost ptr_vector work for you?

0

精彩评论

暂无评论...
验证码 换一张
取 消