STL vector遍历(五)

vector v1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10};

 一、通过数组下标遍历

for (size_t i = 0; i < v1.size(); i++)
{
	cout << v1[i] << "; ";
}
cout << endl;

for (size_t i = 0; i < v1.size(); i++)
{
    cout << v1.at(i) << "; ";
}
cout << endl;

2; 3; 4; 5; 6; 7; 8; 9; 10; 10; 10;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 10;

二、通过迭代器遍历 


for (vector::iterator iter = v1.begin(); iter != v1.end(); iter++)
{
	std::cout << *iter << "; ";
}
cout << endl;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 10;

三、C++11标准,auto关键字遍历 


for (auto iter = v1.begin(); iter != v1.end(); iter++)
{
    cout << *iter << "; ";
}
cout << endl;

for (auto i : v1)
{
    cout << v1[i] << "; ";
} 
cout << endl;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 10;
1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 10;

四、 for_each加函数

#include 
#include 
#include

using namespace std;


template
void printer(const T& val)
{
    cout << val << "; ";
}

void main()
{
    for_each(v1.cbegin(), v1.cend(), printer);
    cout << endl;
}

1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 10;

 

你可能感兴趣的:(#,【STL标准模板库】)