Skip to content

Instantly share code, notes, and snippets.

@xiongxoy
Last active July 18, 2023 17:48
Show Gist options
  • Save xiongxoy/6037197 to your computer and use it in GitHub Desktop.
Save xiongxoy/6037197 to your computer and use it in GitHub Desktop.
array initialization in c++
/*--! When doing initialization, getting array size is important. */
template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
return std::vector<T>(data, data+N);
}
/*--! statck overflow answear, by David Rodríguez */
// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (sizeof_array( T(&)[N] ))[N]; // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))
/*
Gist for vector initialization in C++, code stolen from StackOverflow :)
*/
static const int arr[] = {16, 2, 77, 29};
std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
std::string arr[] = {"Hello", "World"};
std::vector<std::string> vec( arr, arr + sizeof(arr) / sizeof(arr[0]) );
// only works for C++11
std::vector<std::string> v{"Hello", "World"};
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
template <typename T>
void func( T i ) {
std::cout << i <<"\n";
}
void test1()
{
static const int arr[] = {16, 2, 77, 29};
std::vector<int> vec ( arr, arr + sizeof(arr) / sizeof(arr[0]) );
std::for_each( vec.begin(), vec.end(), func<int> );
}
void test2()
{
std::string arr[] = {"Hello", "World"};
std::vector<std::string> vec( arr, arr + sizeof(arr) / sizeof(arr[0]) );
std::for_each( vec.begin(), vec.end(), func<std::string> );
}
void runAllTests();
int main(int argc, const char *argv[])
{
runAllTests();
return 0;
}
void (*pf[128])(void) = {test1, test2, 0};
void runAllTests()
{
for (int i=0; pf[i] != NULL; i++) {
std::cout << "Test case " <<i+1 <<":"<< std::endl;
pf[i]();
std::cout << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment