Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store fixed length strings inside a std::vector

Tags:

c++

stdvector

I want to mimic a structure:

char [][40] = { "Stack", "Overflow", "Exchange", "Network" };

using a std::vector, so I can populate it at runtime and dynamically change the size of the vector, but keeping the member elements located inside fixed size blocks.

Static initialization is not my question - I can do that using boost::assign or other tricks.

like image 846
karim Avatar asked Sep 15 '26 11:09

karim


2 Answers

I'd use something like Boost.Array:

typedef boost::array<char, 40> arr_t;
std::vector<arr_t> vec;
{
    arr_t arr = { "Stack" };
    vec.push_back(arr);
}
{
    arr_t arr = { "Overflow" };
    vec.push_back(arr);
}
{
    arr_t arr = { "Exchange" };
    vec.push_back(arr);
}
{
    arr_t arr = { "Network" };
    vec.push_back(arr);
}

If you're using a reasonably recent compiler, instead of Boost you can probably use std::array<> (C++11; #include <array>) or std::tr1::array<> (C++03 with TR1; #include <array> or #include <tr1/array>, depending on platform).

like image 64
ildjarn Avatar answered Sep 17 '26 00:09

ildjarn


struct fixed_string { 
    char data[40];

    fixed_string(char const *init);
};

std::vector<fixed_string> whatever;

If you have C++11 (or at least TR1), you probably want to use std::array instead of fixed_string. I think Boost has an equivalent as well.

In case anybody's wondering why I put it in a struct, instead of creating a vector of array directly: because items in a vector need to be copyable and assignable, and a bare array is neither.

like image 40
Jerry Coffin Avatar answered Sep 17 '26 00:09

Jerry Coffin