Copy array to vector

I wrote a small program:

void showrecord() { char *a[]={ "O_BILLABLE_ACCOUNT","O_CUSTOMER_TYPE_INDICATOR", "O_A_PARTY_MSISDN_ID","O_A_PARTY_EQUIPMENT_NUMBER", "O_A_PARTY_IMSI","O_A_PARTY_LOCATION_INFO_CELL_ID", ... }; vector<std::string> fields(a,a+75); cout<<"done!!!"<<endl; } int main() { showrecord(); } 

I have an array of string literals, and I want them to be copied to the vector. I did not find another simple way to do this :( Or if there is any direct way to initialize the vector without using an array, it would be very useful. This will reset the kernel after running the executable in unix. This gives me a warning, although it seems to be:

 Warning 829: "test.cpp", line 12 # Implicit conversion of string literal to 'char *' is deprecated. D_TYPE","O_VARCHAR_5","O_VARCHAR_6","O_VARCHAR_7","O_VARCHAR_8","O_VARCHAR_9"}; 

But the same code works fine on Windows without any problems. I am using the aCC compiler on HPUX.

Please, help! EDIT below is a stack of dump tracks.

 (gdb) where #0 0x6800ad94 in strlen+0xc () from /usr/lib/libc.2 #1 0xabc0 in std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string<char,std::char_traits<char>,std::allocator<char>>+0x20 () #2 0xae9c in std<char const **,std::basic_string<char,std::char_traits<char>,std::allocator<char>> *,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>>::uninitialized_copy+0x60 () #3 0x9ccc in _C_init_aux__Q2_3std6vectorXTQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc__TQ2_3std9allocatorXTQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc____XTPPCc_FPPCcT118_RW_is_not_integer+0x2d8 () #4 0x9624 in showrecord () at test.cpp:13 #5 0xdbd8 in main () at test.cpp:21 
+4
source share
3 answers

Why 75?

Edit

 vector<std::string> fields(a,a+75); 

to

 vector<std::string> fields(a, a + sizeof a / sizeof *a); 

There is no โ€œbetterโ€ way to initialize your vector for C ++ 03, but for C ++ 0x you have access to a more convenient syntax allocated to the C array:

 std::vector<std::string> fields { "O_BILLABLE_ACCOUNT", // ... }; 
+5
source

Try const char* a[] instead of char* a[] . String literals are of type const char* , not char* , and therefore you get a warning.

+4
source

Here's a possible solution that IMO is a little more general - uses a reusable function that works with string arrays of any size:

 #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <vector> template <typename Array, std::size_t Size> std::vector<std::string> make_vector(Array (&ar)[Size]) { std::vector<std::string> v(ar, ar + Size); return v; } int main() { char const* a[] = { "Aa","Bb", "Cc","Dd", "Ee","Ff" }; // copy C-array to vector std::vector<std::string> fields = make_vector(a); // test std::copy(fields.begin(), fields.end(), std::ostream_iterator<std::string>(std::cout, "\n")); } 
+2
source

All Articles