Foreach loop in C++ equivalent of C#

前端 未结 11 1735
礼貌的吻别
礼貌的吻别 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 02:06

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

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

    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)
  • 2020-12-13 02:18

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

    Boost has a macro that will do this for you.

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

    0 讨论(0)
提交回复
热议问题