dynamic - Is it possible to have a dynamically populating Array of char* in C++ -


i have situation this.

declare array of char*; switch(id) { case 1:     add 4 words in array case 2:     add 2 words in array default:     add 1 word in array }  use array here; 

is possible such thing in c++. tried doing not working me.

yes. clean, easy-to-understand, correct, exception-safe code, use vector , string:

std::vector<std::string> v;  switch (id) { case 1:     v.push_back("a");     v.push_back("b");     v.push_back("c");     v.push_back("d");     break;  case 2:     v.push_back("a");     v.push_back("b");     break;  default:     v.push_back("a"); }  // use strings in v; example, using c++11 lambda expression: std::for_each(begin(v), end(v), [](std::string const& s) {     std::cout << s << std::endl; });  // or using loop: (std::vector<std::string>::const_iterator it(v.begin()); != v.end(); ++it) {     std::cout << *it << std::endl; } 

of course, can accomplish similar results using manual dynamic allocation , cleanup of both array , c strings, , ensure code correct , exception-safe more difficult , require substantially more code.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -