Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop in C++ equivalent of C#

Tags:

c++

c#

How would I convert this code to C++?

string[] strarr = {"ram","mohan","sita"};     foreach(string str in strarr) {   listbox.items.add(str); } 
like image 235
Swapnil Gupta Avatar asked Sep 06 '10 04:09

Swapnil Gupta


People also ask

What can I use instead of forEach?

The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.

What is the syntax of foreach loop?

How foreach loop works? The in keyword used along with foreach loop is used to iterate over the iterable-item . The in keyword selects an item from the iterable-item on each iteration and store it in the variable element . On first iteration, the first item of iterable-item is stored in element.

Does C have continue?

The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration.

How do forEach loops work in C++?

Working of the foreach loop in C++ So basically a for-each loop iterates over the elements of arrays, vectors, or any other data sets. It assigns the value of the current element to the variable iterator declared inside the loop.


1 Answers

ranged based for:

std::array<std::string, 3> strarr = {"ram", "mohan", "sita"}; for(const std::string& str : strarr) {   listbox.items.add(str); } 

pre c++11

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

Using Boost:

boost::array<std::string, 3> strarr = {"ram", "mohan", "sita"}; BOOST_FOREACH(std::string & str, strarr) {   listbox.items.add(str); } 
like image 129
missingfaktor Avatar answered Oct 06 '22 01:10

missingfaktor