#include <iostream>
#include <vector>
using namespace std;
int vector02(); //全局函数要在使用前事先声明
class student {
public:
student(int a) {
}
~student() {
}
student(const student& stu) {
}
student& operator=(const student& stu) {
}
int vector03(); //函数声明(在类内部)
};
int student::vector03() { //函数的定义(在类外部)
vector<double> v3(20); //调用了vector的某一个被重载的构造函数,意义是 v3的长度是20
vector<double> v4(v3); //调用了vector的拷贝构造函数(根据传参的类型和个数)
//方法1:通过数组下标访问vector动态数组
for (int i = 0; i < v3.size(); ++i) {
v3[i] = i;
}
for (int i = 0; i < v3.size(); ++i)
{
cout << v3[i] << endl;
}
v3.clear(); //清空v3,重新赋值
v3.resize(20);
std::cout << "----------------------------" << std::endl;
//方法2:通过iterator迭代器访问
vector<double>::iterator iter;
for (iter = v3.begin(); iter != v3.end(); iter++) {
*iter = 99;
}
for (iter = v3.begin(); iter != v3.end(); iter++)
{
cout << *iter << endl;
}
return 0;
}
int main() {
vector<int> v;
//v[0] = 10; //error!! 容器vector还未初始化,不能赋值
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//方法一:用数组的方式输出
for (unsigned int i = 0; i < v.size() ; i++)
{
cout << v[i] << " ";
}
cout << "-------" << endl;
//方法二:用迭代器(iterator)的方式输出
//1-定义迭代器
vector<int>::iterator iter;
for (iter = v.begin(); iter != v.end(); iter++) {
cout << *iter << " ";
}
cout << endl;
//vector02();
student s1(10);
s1.vector03();
return 0;
}
//多种方法遍历vector容器
int vector02() {
vector<int> v2(20); //
for (int i = 0; i < v2.size(); ++i) {
v2[i] = i;
cout << "v2用数组方式打印:" << v2[i] << " " << "\n";
v2[i] = i * 2;
}
cout << endl;
for (vector<int>::iterator iter=v2.begin(); iter != v2.end(); ++iter)
{
cout << "v2用迭代器方式打印:" << *iter << " " << endl;
}
return 0;
}