Reputation: 9391
Is there any way to do this:
std::vector<char[foo]> bar;
I need ONE contiguous array of char[foo]
but I don't know the length until runtime. I need to be able to add blocks of char[foo]
dynamically.
I need the inner array to be exactly the right size, so if foo
was 3:
[ [1, 2, 3] [4, 5, 6] ... [x, y, z] ]
I could implement it myself but don't want to reinvent the wheel.
Upvotes: 3
Views: 151
Reputation: 7970
After the question was reworded, you're probably looking for std::vector< std::array<char, 3> >
Memory will be contiguous for all elements. Assuming the last dimentsion is indeed a build time const.
Example:
std::vector< std::array<char, 3> > bar;
std::array<char, 3> foo = { 'a', 'b', 'c' };
bar.insert(bar.end(), 10, foo);
Upvotes: 0
Reputation: 179917
I'd create a container class myself, use std::vector<char>
internally, and create a wrapper slice
class which holds a pointer to the container class and an index into the vector. The container class would hold the length foo
. The container would have an iterator returning slices, each slice
would have an iterator returning char
.
[edit] This solution also allocates contiguous memory.
Upvotes: 3
Reputation: 38173
I'd suggest using
std::vector< std::vector< char > >
std::vector
's internal memory is continuous.
Well, after a while, it appeared, that the whole memory must be continuous, which changes everything..
For this case, you can use directly std::vector< char >::insert( pos, begin, end )
to insert
whole "chunks".
Something like: (I didn't test it, but you'll get the idea)
std::vector< char > bar;
// ..
{
std::vector< char > buff( foo );
// fill buff
bar.insert( bar.end(), buff.begin(), buff.end() );
}
Only keep in mind, that this may/will cause reallocation of the internal memory and several copies of the elements, but we're talking about char
, so it's not a big deal.
You can avoid these reallocations using std::vector::reserve
, if you have idea about the final size of bar
.
Upvotes: 5
Reputation: 1
std::vector<char> bar(foo)
Constructs foo chars with in the vector, but because char is a built in type the constructor won't be called so it will be garbage values until initialised.
Instead use std::vector<char> bar(foo, char())
to fill it with initialised chars.
Upvotes: -3