C++11的for循环使用auto的新用法
for(auto a:vec)
{
cout<<a<<" ";
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vec;
for(int i=0; i<10; i++)
{
vec.push_back(i);
}
for(auto a:vec)
{
cout<<a<<" ";
}
cout << endl;
vector<int>::iterator it = vec.begin();
for (it; it != vec.end();it++)
{
cout << *it << " ";
}
system("pause");
return 0;
}
void printLN(T value)
{
cout << value <<" ";
}
for_each(vec.begin(), vec.end(), printLN);
for_each(iterator,iterator,callback);
前两个参数列表是遍历容器的迭代器,第三个参数是对应的回调函数
回调函数的原理都是将参数传递至相应的函数体,再进行操作
#include<bits/stdc++.h>
using namespace std;
template<typename T>
void printLN(T value)
{
cout << value <<" ";
}
int main()
{
vector<int> vec;
for(int i=0; i<10; i++)
{
vec.push_back(i);
}
for_each(vec.begin(), vec.end(), printLN<int>);
system("pause");
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
//array
int array[] = {1, 2, 3, 4, 5};
for(auto a:array)
{
cout << a << " ";
}
cout << endl;
//string
string str = "hello world!";
for(auto b:str)
{
cout << b << " ";
}
cout << endl;
//vector
vector<int> vec = {1, 3, 5, 7};
for(auto c:vec)
{
cout << c << " ";
}
cout << endl;
//map
map<int, string> mymap = {{1, "abc"}, {2, "bca"}, {3, "acb"}};
for(auto d:mymap)
{
cout << d.first << " " << d.second << " ";
}
cout << endl;
cout << "另一种方式:";
for (map<int, string>::iterator it = mymap.begin(); it != mymap.end(); it++)
{
cout<< it->first<<" "<<it->second<< " ";
}
cout << endl;
system("pause");
return 0;
}