C++ for

通过 : 遍历

C++新标准提供的范围for语句。这种语句遍历给定序列中个元素并对序列中每一个值执行某种操作,其语法形式是:

  1. for(declaration : expression)
  2. statement

其中,expression部分是一个对象,用于表示一个序列。declaration部分负责定义一个变量,该变量将用于访问序列中的基础元素。每次迭代,declaration部分的变量会被初始化为expression部分的下一个元素值
例子:

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. string str("this is a c++");
  6. //每行输出str中的一个字符
  7. for(auto c : str)
  8. cout<<c<<endl;
  9. system("pause");
  10. return 0;
  11. }

代码输出:

  1. t
  2. h
  3. i
  4. s
  5. i
  6. s
  7. a
  8. c
  9. +
  10. +
  11. 请按任意键继续. . .

通过遍历的对象的长度进行循环

代码中的 auto 关键字让编译器来决定 c的类型,每次迭代后,str的下一个字符赋值给 c
看看比较正常的 for 语句

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. string str("this is a c++");
  6. for(int i = 0;i<str.length();i++)
  7. cout<<str.at(i)<<endl;
  8. system("pause");
  9. return 0;
  10. }

输出:

  1. t
  2. h
  3. i
  4. s
  5. i
  6. s
  7. a
  8. c
  9. +
  10. +
  11. 请按任意键继续. . .

通过字符串的 begin()end() 方法

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. string str("this is a c++");
  6. for(auto i = str.begin(); i!= str.end();++i)
  7. cout<<(*i)<<endl;
  8. system("pause");
  9. return 0;
  10. }

输出

  1. t
  2. h
  3. i
  4. s
  5. i
  6. s
  7. a
  8. c
  9. +
  10. +
  11. 请按任意键继续. . .

通过STL函数

使用STL函数,需要包含头文件。

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5. int main()
  6. {
  7. string str("this is a c++");
  8. for_each(str.begin(),str.end(),[](char item)
  9. {
  10. cout<<item << " ";
  11. });
  12. system("pause");
  13. return 0;
  14. }

输出

  1. t h i s i s a c + + 请按任意键继续. . .