C++for循环总结

//字符串
#include <iostream> 
//for_each
#include <algorithm>
//数组vector相关操作
#include <vector>

using namespace std;

struct Play {
    Play() {
        cout << "new a Play" << endl;
    }

    Play(const Play &) {
        cout << "new a copy Play" << endl;
    }

    Play(const char *s) {
        cout << s<< endl;
    }
    void operator()(int i) {
        cout << i << endl;
    }

    ~Play() {
        cout << "dispose a Play" << endl;
    }
};

void fun(int i) {
    cout << "for_each(v.begin(), v.end(), fun)" << i << endl;
}

void getArray() {
    int num[5] = {1, 3, 1, 4};
    //这个x *= 2 会改变数组内容
    for (int &x : num) {
        x *= 2;
        cout << "for (int &x : num)" << x << endl;
    }

    //生成迭代器
    vector<int> v(num, num + sizeof(num) / sizeof(int));
    //无参调用fun
    for_each(v.begin(), v.end(), fun);
    //有参调用
    for_each(v.begin(), v.end(), Play("Element:"));

    //迭代器 for循环
    for (auto it = v.begin(); it != v.end(); ++it) {
        cout << " for (auto it = v.begin(); it != v.end(); ++it) " << *it << endl;
    }

    //这种最简单
    for (auto item : num) {
        cout << "for(auto item : num)" << item << endl;
    }

    //字符串遍历 转成大写
    string str("some string");
    for (auto &c : str) {
        c = toupper(c);
    }
    cout << str << endl;
}

打印结果

for (int &x : num)2
for (int &x : num)6
for (int &x : num)2
for (int &x : num)8
for (int &x : num)0
for_each(v.begin(), v.end(), fun)2
for_each(v.begin(), v.end(), fun)6
for_each(v.begin(), v.end(), fun)2
for_each(v.begin(), v.end(), fun)8
for_each(v.begin(), v.end(), fun)0
new a Play
2
6
2
8
0
new a copy Play
dispose a Play
dispose a Play
Element:
2
6
2
8
0
new a copy Play
dispose a Play
dispose a Play
for (auto it = v.begin(); it != v.end(); ++it) 2
for (auto it = v.begin(); it != v.end(); ++it) 6
for (auto it = v.begin(); it != v.end(); ++it) 2
for (auto it = v.begin(); it != v.end(); ++it) 8
for (auto it = v.begin(); it != v.end(); ++it) 0
for(auto item : num)2
for(auto item : num)6
for(auto item : num)2
for(auto item : num)8
for(auto item : num)0
SOME STRING

总结:
1.c++的遍历和JAVA完全不同,着实麻烦,用哪种方式就是仁者见仁。
2.for_each的遍历还远不止这么简单,感兴趣可以移步C++ for_each高级用法
3. int num[5] = {1, 3, 1, 4}; 其中第五位默认为0
4. 从打印结果看Play 构造函数和java一致,但是两次析构却是for_each造成的:参考2

猜你喜欢

转载自blog.csdn.net/qq_20330595/article/details/82108123