How would I convert this code to C++?
string[] strarr = {\"ram\",\"mohan\",\"sita\"};
foreach(string str in strarr) {
listbox.items.add(str);
}
std::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
for(const std::string& str : strarr) {
listbox.items.add(str);
}
std::string strarr[] = {"ram", "mohan", "sita"};
for(int i = 0; i < 3; ++i) {
listbox.items.add(strarr[i]);
}
or
std::string strarr[] = {"ram", "mohan", "sita"};
std::vector<std::string> strvec(strarr, strarr + 3);
std::vector<std::string>::iterator itr = strvec.begin();
while(itr != strvec.end()) {
listbox.items.add(*itr);
++itr;
}
boost::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
BOOST_FOREACH(std::string & str, strarr) {
listbox.items.add(str);
}
string[] strarr = {"ram","mohan","sita"};
#include <string>
std::string strarr = { "ram", "mohan", "sita" };
or
const char* strarr[] = { "ram", "mohan", "sita" };
foreach(string str in strarr) { listbox.items.add(str); }
for (int i = 0; i < sizeof strarr / sizeof *strarr; ++i)
listbox.items.add(strarr[i]);
Note: you can also put the strings into a std::vector rather than an array:
std::vector<std::string> strvec;
strvec.push_back("ram");
strvec.push_back("mohan");
strvec.push_back("sita");
for (std::vector<std::string>::const_iterator i = strvec.begin(); i != strvec.end(); ++i)
listbox.items.add(*i);
If you have an array you can simply use a for
loop. (I'm sorry, but I'm not going to type out the code for a for
loop for you.)
Using boost is the best option as it helps you to provide a neat and concise code, but if you want to stick to STL
void listbox_add(const char* item, ListBox &lb)
{
lb.add(item);
}
int foo()
{
const char* starr[] = {"ram", "mohan", "sita"};
ListBox listBox;
std::for_each(starr,
starr + sizeof(starr)/sizeof(char*),
std::bind2nd(std::ptr_fun(&listbox_add), listBox));
}
Boost has a macro that will do this for you.
http://www.boost.org/doc/libs/1_44_0/doc/html/foreach.html