I am trying to write a program that has a vector of char arrays and am have some problems.
char test [] = { \'a\', \'b\', \'c\', \'d\', \'e\' };
vector
Use std::string
instead of char-arrays
std::string k ="abcde";
std::vector<std::string> v;
v.push_back(k);
You can directly define a char type vector as below.
vector<char> c = {'a', 'b', 'c'};
vector < vector<char> > t = {{'a','a'}, 'b','b'};
FFWD to 2019. Although this code worketh in 2011 too.
// g++ prog.cc -Wall -std=c++11
#include <iostream>
#include <vector>
using namespace std;
template<size_t N>
inline
constexpr /* compile time */
array<char,N> string_literal_to_array ( char const (&charrar)[N] )
{
return std::to_array( charrar) ;
}
template<size_t N>
inline
/* run time */
vector<char> string_literal_to_vector ( char const (&charrar)[N] )
{
return { charrar, charrar + N };
}
int main()
{
constexpr auto arr = string_literal_to_array("Compile Time");
auto cv = string_literal_to_vector ("Run Time") ;
return 42;
}
Advice: try optimizing the use of std::string
. For char buffering std::array<char,N>
is the fastest, std::vector<char>
is faster.
https://wandbox.org/permlink/wcasstoY56MWbHqd
You can use boost::array to do that:
boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);
Edit:
Or you can use a vector of vectors as shown below:
char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));
You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.
If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct:
struct S {
char a[10];
};
and then create a vector of structs:
vector <S> v;
S s;
s.a[0] = 'x';
v.push_back( s );
What I found out is that it's OK to put char* into a std::vector:
// 1 - A std::vector of char*, more preper way is to use a std::vector<std::vector<char>> or std::vector<std::string>
std::vector<char*> v(10, "hi!"); // You cannot put standard library containers e.g. char[] into std::vector!
for (auto& i : v)
{
//std::cout << i << std::endl;
i = "New";
}
for (auto i : v)
{
std::cout << i << std::endl;
}