C++for循环的5种⽤法
介绍了C++ for 循环的5种⽤法。通过这⾥的案例,也可以熟悉对string 容器的使⽤。可以通过[] 来访问string 对象。for each
std::for_each
for  in
for :
for
#include <iostream>
#include <map>
#include <vector>
#include <string>
printf怎么加endl
#include <unordered_map>
#include <algorithm>
using namespace std;
void TestFor()
{
int nArray[] = { 5,4,3,2,1,666,777 };
std::vector<int> vecNum(nArray, nArray + 6);
string strText = "ABCDEFGHIJKLMN";
//第1种⽤法
cout << "========for 1:" << endl;
for (int i = 0; i < vecNum.size(); ++i)
{
printf("(%d,%d) ", i, vecNum[i]);
}
cout << endl;
for (int i = 0; i < strText.size(); ++i)
{
printf("(%d,%c), ", i, strText[i]);
}
cout << endl << endl;
//第2种⽤法
cout << "========for 2:" << endl;
for (std::vector<int>::iterator it = vecNum.begin(); it != d(); ++it)
{
printf("%d, ", *it);
}
cout << endl;
for (auto it = strText.begin(); it != d(); ++it)
{
printf("%c, ", *it);
}
cout << endl << endl;
//第3种⽤法
cout << "========for 3: for each" << endl;
for each(auto item in vecNum)
{
printf("%d, ", item);
}
cout << endl;
for each(auto item in strText)
{
printf("%c, ", item);
}
cout << endl << endl;
//第4种⽤法
cout << "========for 4: std::for_each  需要包含<algorithm>" << endl;
std::for_each(vecNum.begin(), d(), [](int item) {
printf("%d, ", item);
});
cout << endl;
std::for_each(strText.begin(), d(), [](int item) {
printf("%c, ", item);
});
cout << endl << endl;
//第5种⽤法
cout << "========for 5: " << endl; for (auto item : vecNum)
{
printf("%d, ", item);
}
cout << endl;
for (auto item : strText)
{
printf("%c, ", item);
}
cout << endl << endl;
}
int main()
{
TestFor();
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。