目录
遍历输出的方法:
<默认数据>
<自定义数据>
嵌套vector>
遍历输出的方法:
1、使用for循环输出
2、调用for_each()函数 // 需要添加头文件#include <algorithm>
<默认数据>
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>/*algorithm意为"算法",是C++的标准模版库(STL)中最重要的头文件之一,提供
了大量基于迭代器的非成员模版函数*/
void myprint(int temp)
{
cout << temp << endl;
}
int main()
{
vector<int> sys;
sys.push_back(001);
sys.push_back(004);
sys.push_back(003);
sys.push_back(002);
//第一种,推荐
for (vector<int>::iterator bg = sys.begin(); bg != sys.end(); bg++)
{
cout << *bg<<endl;
}
//第二种,也行,本质也是for循环
for_each(sys.begin(), sys.end(), myprint);
return 0;
}
<自定义数据>
#include <iostream>
#include <string>
using namespace std;
#include <vector>
#include <algorithm>
class person
{
public:
person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void text001()
{
vector<person>v;
person p1("aaa", 1);
person p2("bbb", 2);
person p3("ccc", 3);
person p4("ddd", 4);
person p5("eee", 5);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
for (vector<person>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << (*it).m_name << " " << (*it).m_age << endl;
cout << it->m_name << " " << it->m_age << endl;
}
}
void text002()
{
vector<person*>v;
person p1("aaa", 1);
person p2("bbb", 2);
person p3("ccc", 3);
person p4("ddd", 4);
person p5("eee", 5);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
for (vector<person*>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << (**it).m_name << " " << (**it).m_age << endl;
cout << (*it)->m_name << " " << (*it)->m_age << endl;
}
}
int main()
{
text001();
text002();
return 0;
}
*it 指代 “ <> ”中的类型,it可以简单的理解为指针(早期);
<vector嵌套vector>
别把自己套进去就行
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
int main()
{
vector<vector<int>>v;
vector<int>v1;
vector<int>v2;
vector<int>v3;
vector<int>v4;
for (int i = 0; i < 5; i++)
{
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
v4.push_back(i + 4);
}
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++)
{
//*it为vector<int>
for (vector<int>::iterator vit = (*it).begin();vit!=(*it).end();vit++)
{
cout << *vit << " ";
}
cout << endl;
}
return 0;
}
|