Container of buffers

A

Alex Vinokur

I need a container of char-buffers, for instance, vector of
char-buffers.

vector<string> v; // It is not what I need to

char a[10];
memset (&a[0], 0, sizeof (a));

v.push_back(a);

cout << v.back(); // This displays empty string, not 10 bytes. I need
to get 10 bytes in this example.

Is there any way to create a container of char-buffers?


Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
 
J

Jakob Bieling

Alex Vinokur said:
I need a container of char-buffers, for instance, vector of
char-buffers.

vector<string> v; // It is not what I need to

I would say this would work, if used right. But there are other
solutions.
char a[10];
memset (&a[0], 0, sizeof (a));

v.push_back(a);

Because v is a vector of strings, a temporary std::string object is
constructed based on 'a'. That means 'a' is treated like a C-style
string. Because 'a' contains all '\0' values, the char-array contains an
empty C-string, which is why the std::string object is also empty.
cout << v.back(); // This displays empty string, not 10 bytes. I need
to get 10 bytes in this example.
Is there any way to create a container of char-buffers?

std::vector <std::string> v;
v.resize (20, std::string (10, 0));

Now 'v' contains 20 strings. Each of those contains 10 0-chars. Note
that you can dynamically change the size of each string. Instead of
using a std::string, you could also use a std::vector.

Another approach is to create a struct:

struct char_buffer
{
char data [10];
};

std::vector <char_buffer> v;
v.resize (20);


Now 'v' contains 20 'char_buffer' objects. Each of those contains 10
chars. Note that now you cannot dynamically change the size of each
char_buffer anymore.

hth
 
F

flagos

Alex. Try something like the following:

typedef std::vector<std::string> my_container;

my_container c;

std::string s1(10,' ');

c.push_back( s1 );


Hope this help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top