80

How would I convert this code to C++?

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

11 Answers 11

127

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);
}
5
  • 3
    @ronag: The accepted answer here reflects my opinion about std::for_each. Commented Sep 6, 2010 at 10:41
  • 2
    What about regarding the size of the array like for(int i = 0; i < sizeof(strarr)/sizeof(strarr[0]); i++) in the first code example?
    – Thorben
    Commented Jan 10, 2014 at 19:35
  • since C++11 is 6 years old and 3 standards back, may I suggest moving the C++11 part of the question to the top. In fact, let's assume C++11 as default and don't mention C++. In stead mention C++98 for the other.
    – bolov
    Commented Nov 20, 2017 at 21:55
  • @bolov, this is a seven years old answer, mate. I have not written C++ for six years now. Please feel free to update the answer as you see fit. Commented Nov 21, 2017 at 0:53
  • @missingfaktor sure, no problem
    – bolov
    Commented Nov 21, 2017 at 11:16
29

In C++0x you have

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

But till then use ordinary for loop.

14

After getting used to the var keyword in C#, I'm starting to use the auto keyword in C++11. They both determine type by inference and are useful when you just want the compiler to figure out the type for you. Here's the C++11 port of your code:

#include <array>
#include <string>

using namespace std;

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

Boost has a macro that will do this for you.

http://www.boost.org/doc/libs/1_44_0/doc/html/foreach.html

2
  • I know Google sucks in this regard, so not your fault, but the latest version is 1.44, so the link should container 1_44, not 1_35. (You'll have to fix Google results by hand.)
    – GManNickG
    Commented Sep 6, 2010 at 4:31
  • Thanks. I have 1.44 downloaded and built on my system, but wasn't thinking about the version when I posted that.
    – user439793
    Commented Sep 6, 2010 at 12:20
5

Just for fun (new lambda functions):

      static std::list<string> some_list;

      vector<string> s; 
      s.push_back("a");
      s.push_back("b");
      s.push_back("c");

      for_each( s.begin(), s.end(), [=](string str) 
        {
          some_list.push_back(str);
        }

  );

  for_each( some_list.begin(), some_list.end(), [](string ss) { cout << ss; } );

Although doing a simple loop is recommended :-)

2

Something like:

const char* strarr = {"ram","mohan","sita", 0L};

for(int i = 0; strarr[i]; ++i)
{
  listbox.items.add(strarr[i]);
}

Also works for standard C. Not sure in C++ how to detect the end of the strarr without having a null element, but the above should work.

2
  • If it's a statically allocated array, then sizeof(strarr)/sizeof(strarr[0]) gets you the number of elements in the array; however, if it's a dynamically allocated array (or if all you have is a pointer), then there's no way to get the size -- you have to get it by some other out-of-band means. Commented Sep 6, 2010 at 4:28
  • The correct type for the size of (and thus an index into) an array is std::size_t.
    – sbi
    Commented Sep 6, 2010 at 5:17
1

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

The simple form:

std::string  data[] = {"ram","mohan","sita"};
std::for_each(data,data+3,std::bind1st(std::mem_fun(&Y::add), &(listbox.items)));

An example in action:

#include <algorithm>
#include <string>
#include <iostream>
#include <functional>

class Y
{
    public:
      void add(std::string value)
      {
          std::cout << "Got(" << value << ")\n";
      }
};
class X
{
    public:
      Y  items;
};

int main()
{
    X listbox;

    std::string  data[] = {"ram","mohan","sita"};
    std::for_each(data,data+3,std::bind1st(std::mem_fun(&Y::add), &(listbox.items)));
}
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.)

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

}
0

using C++ 14:

#include <string>
#include <vector>


std::vector<std::string> listbox;
...
std::vector<std::string> strarr {"ram","mohan","sita"};    
for (const auto &str : strarr)
{
    listbox.push_back(str);
}
1
  • Can this not be abbreviated to for (const auto &str : {"ram","mohan","sita"} ) ... ? Commented Feb 1, 2019 at 0:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.