Reputation: 333
I need to design an efficient and readable class with 2 main functions:
add_buffer(char* buffer)
- add a buffer.char* read_all()
- get one big buffer that contains all the buffers that the user added until now (by order).for example:
char first_buffer[] = {1,2,3};
char second_buffer[] = {4,5,6};
MyClass instance;
instance.add_buffer(first_buffer);
instance.add_buffer(second_buffer);
char* big_buffer = instance.read_all(); // big_buffer = [1,2,3,4,5,6]
NOTE: There are a lot of solutions for this problem but I'm looking for an efficient one because in real life the buffers will be many and big, and I want to save a lot of copying and reallocs (like what std::vector does). I'm also want a readble c++ code.
NOTE: The real life problem is: I'm reading data from an HTTP request that came to me at separated chunks. After all chunks arrived I want to return the whole data to the user.
Upvotes: 3
Views: 2414
Reputation: 40070
Use an std::vector<char>
with enough memory reserved. Since C++11, you can access the internal buffer with std::vector::data()
(until C++11, you had to use &*std::vector::begin()
).
Upvotes: 9
Reputation: 5606
If you can use Boost, boost::algorithm::join
will do:
#include <boost/algorithm/string/join.hpp> #include <vector> #include <iostream> int main(int, char **) { std::vector<std::string> list; list.push_back("Hello"); list.push_back("World!"); std::string joined = boost::algorithm::join(list, ", "); std::cout << joined << std::endl; }
Output:
Hello, World!
Original answer by Tristram Gräbener
Upvotes: 2
Reputation: 169
Use some standard approach like,
If you don't want to do it yourself, use STL containers like
std::vector<char>
It automatically reallocates memory for you when buffer is full.
Upvotes: 0