STL容器中的for循环遍历方式
淮上喜会梁川故友 韦应物
江汉曾为客,相逢每醉还。
浮云一别后,流水十年间。
欢笑情如旧,萧疏鬓已斑。
何因不归去,淮上有秋山。
在遍历容器中的元素时,一般我们会使用如下的几种遍历方式。
普通的for循环
- for (int i_loop = 0; i_loop < st.size(); i_loop++)
- 利用set的size作为循环条件。
code:
#include <iostream>
#include <set>
using namespace std;
template<typename T>
void print_set_normal(const set<T>& st)
{
set<int>::iterator it = st.begin();
for (int i_loop = 0; i_loop < st.size(); i_loop++)
{
cout << *it << " ";
it++;
}
cout << endl;
}
void test01()
{
set<int> st1{23, 1, 56, 78, 44, 35, 99, 76}; // 初始化列表构造函数
cout << "---------- st1, st1.size() ---------- " << st1.size() << endl;
print_set_normal(st1);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
result:
---------- st1, st1.size() ---------- 8
1 23 35 44 56 76 78 99
利用迭代器for循环
- for (set::iterator it = st.begin(); it != st.end(); it++)
- 利用迭代器begin(), end()作为循环条件,有的容器不支持<,可以用!=。
code:
#include <iostream>
#include <set>
using namespace std;
template<typename T>
void print_set_iterator(const set<T>& st)
{
for (set<int>::const_iterator it = st.begin(); it != st.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test01()
{
set<int> st1{23, 1, 56, 78, 44, 35, 99, 76}; // 初始化列表构造函数
cout << "---------- st1, st1.size() ---------- " << st1.size() << endl;
print_set_iterator(st1);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
result:
---------- st1, st1.size() ---------- 8
1 23 35 44 56 76 78 99
for循环新用法 for (auto i_st : st)
- for (auto i_st : st)
code:
#include <iostream>
#include <set>
using namespace std;
template<typename T>
void print_set_for_auto(const set<T>& st)
{
for (auto i_st : st) // auto在这里表示自动类型推导,在这里也可以for (int i_st1: st1)
{
cout << i_st << " ";
}
cout << endl;
}
void test01()
{
set<int> st1{23, 1, 56, 78, 44, 35, 99, 76}; // 初始化列表构造函数
cout << "---------- st1, st1.size() ---------- " << st1.size() << endl;
print_set_for_auto(st1);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
result:
---------- st1, st1.size() ---------- 8
1 23 35 44 56 76 78 99
for_each循环
- for_each(st.begin(), st.end(), func)
- 要使用for_each,先要导入头文件,#include <algorithm>
code:
#include <iostream>
#include <set>
using namespace std;
template<typename T>
void print_set_for_auto(const set<T>& st)
{
for (auto i_st : st) // auto在这里表示自动类型推导,在这里也可以for (int i_st1: st1)
{
cout << i_st << " ";
}
cout << endl;
}
void test01()
{
set<int> st1{23, 1, 56, 78, 44, 35, 99, 76}; // 初始化列表构造函数
cout << "---------- st1, st1.size() ---------- " << st1.size() << endl;
print_set_for_auto(st1);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
result:
---------- st1, st1.size() ---------- 8
1 23 35 44 56 76 78 99

4万+

被折叠的 条评论
为什么被折叠?



