Alex Rivera | Logout

Foreach loop in C++ equivalent of C#

Asked 2010-09-06T04:11:18.247
80

How would I convert this code to C++?

string[] strarr = {"ram","mohan","sita"};    
foreach(string str in strarr) {
  listbox.items.add(str);
}
Edit
Report

3 Answers

29

In C++0x you have

for(string str: strarr) { ... }

But till then use ordinary for loop.

answered 2010-09-06T04:15:20.497
0

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.)

answered 2010-09-06T04:14:04.010
0

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));

}
answered 2010-09-06T04:59:31.307

Your Answer