在C++中实现foreach循环

来源:互联网 发布:微信收款盒子对接端口 编辑:程序博客网 时间:2024/06/05 08:14

foreach实现

#define foreach(container,it) \    for(typeof((container).begin()) it = (container).begin();it!=(container).end();++it)

C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC’s typeof, then a similar feature is present in C++11 through the keywords decltype and auto. Again, C++ has no such typeof keyword.
typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.
Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various “names” are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.
Note also, that the above probably implies (although the standard doesn’t seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

so:

#define foreach(container,it) \    for(auto it = (container).begin(); it != (container).end(); ++it)

std::for_each Demo

// 原型Function for_each (InputIterator first, InputIterator last, Function f);
// for_each example#include <iostream>#include <algorithm>#include <vector>using namespace std;void myfunction (int i) {  cout << " " << i;}struct myclass {  void operator() (int i) {cout << " " << i;}} myobject;int main () {  vector<int> myvector;  myvector.push_back(10);  myvector.push_back(20);  myvector.push_back(30);  cout << "myvector contains:";  for_each (myvector.begin(), myvector.end(), myfunction);  // or:  cout << "\nmyvector contains:";  for_each (myvector.begin(), myvector.end(), myobject);  cout << endl;  return 0;}
0 0
原创粉丝点击