Foreach loop in C++ equivalent of C#

前端 未结 11 1734
礼貌的吻别
礼貌的吻别 2020-12-13 01:20

How would I convert this code to C++?

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


        
相关标签:
11条回答
  • 2020-12-13 01:58

    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.

    0 讨论(0)
  • 2020-12-13 01:59

    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);
    }
    
    0 讨论(0)
  • 2020-12-13 02:01

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

    0 讨论(0)
  • 2020-12-13 02:02

    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 讨论(0)
  • 2020-12-13 02:05

    In C++0x you have

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

    But till then use ordinary for loop.

    0 讨论(0)
  • 2020-12-13 02:05

    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);
    }
    
    0 讨论(0)
提交回复
热议问题