我如何将这段代码转换为C++?

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

最佳答案

ranged based for:

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

C++ 11之前的版本
std::string strarr[] = {"ram", "mohan", "sita"};
for(int i = 0; i < 3; ++i) {
  listbox.items.add(strarr[i]);
}

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

使用Boost:
boost::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
BOOST_FOREACH(std::string & str, strarr) {
  listbox.items.add(str);
}

关于c# - 与C#等效的C++中的Foreach循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3648951/

10-09 07:18