C++ 11 笔记 (二) : for循环

首先肯定的是,我不是标题党。。

C++11的for循环确实有跟C++98不一样的地方,还是先上代码:

1 int test_arr[] = { 1, 2, 3, 4, 5 };
2 for (int x : test_arr)
3 {
4     std::cout << x << std::endl;
5 }

看上去跟Java的for循环和C#的foreach很相似,但是Java和C#的for循环是只读的,而C++的可以读写,我们把上面的代码修改成这样:

1 for (int &x : test_arr)
2 {
3     x = 8;
4 }

这样数组中的元素就全都是8了,而Java和C#是不允许修改的。。

这种好东西肯定不能少了std::vector, std::map, std::set这三个神器了,迭代器模式当年可是一种设计模式啊,现在却直接在语言中集成了,又少了一种秀操作的手段。(呵呵呵呵。。)

std::vector<int> test_vector;
test_vector.push_back(6);
test_vector.push_back(7);
test_vector.push_back(8);
test_vector.push_back(9);
test_vector.push_back(10);
for (int x : test_vector)
{
    std::cout << x << std::endl;
}

std::map<std::string, std::string> test_map;
test_map.insert(std::pair<std::string, std::string>("约翰", "电锯叔叔"));
test_map.insert(std::pair<std::string, std::string>("吉尔", "电锯婶婶"));
test_map.insert(std::pair<std::string, std::string>("阿曼达", "电锯姐姐"));

for (std::pair<std::string, std::string> test_pair : test_map)
{
    std::cout << test_pair.first << std::endl;
    std::cout << test_pair.second << std::endl;
}

std::set<int> test_set;
test_set.insert(16);
test_set.insert(17);
test_set.insert(18);
test_set.insert(19);
test_set.insert(20);
for (int x : test_set)
{
    std::cout << x << std::endl;
}

另外还有一点,std::vector是可读写的,但是std::map和std::set是只读的,因为已经声明了const。

算得上废话么,弱弱问一句。。。

另外我很喜欢《电锯惊魂》系列,请无视std::map例子中的字符串。。。

——————————————

4-23 9:43 补充:

std::string也可以的,代码就不加了。。

原文地址:https://www.cnblogs.com/wolfred7464/p/3683960.html