1. 程式人生 > 其它 >初識容器 演算法 迭代器

初識容器 演算法 迭代器

問題:
stl概念,好處,包含什麼?
哪6大元件

vector容器

自定義資料型別迭代器輸入,輸出方法

  • vector<資料型別>::iterator 可將迭代器視為指標
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class person {
public:
    person(string name, int age) {
        this->name = name;
        this->age = age;
    }
public:
    string name;
    int age;
};
void MyPrint(person p)
{
    cout << "name:" << p.name << endl;
    cout << "age:" << p.age << endl;
}
//1.內建函式法
 void outputfunc1(vector<person>v){
    cout << "outputfunc1**********" << endl;
    for_each(v.begin(), v.end(), MyPrint);
    cout << v.begin()->name << endl;
    cout << v.begin()->age << endl;
 }
//2.迭代器指標法 -> 法for迴圈遞增指標位置
void outputfunc2(vector<person>v) {
    cout << "outputfunc2*********" << endl;
    for (vector<person>::iterator it = v.begin(); it != v.end(); it++) {
        cout << "name:" << it->name << endl;
        cout << "age:" << it->age << endl;
    }
}
//2.迭代器指標法 * 法
 void outputfunc3(vector<person>v){
     cout << "outputfunc3*********" << endl;
     for (vector<person>::iterator it=v.begin(); it != v.end(); it++) {
         cout<<"---name:"<<(*it) .name << endl;
         cout<<"---age:"<< (*it).age <<endl;//(*it).age和*it.age不同,會誤認為指向it.age
     }
 }
 //2.迭代器指標法 常規while迴圈
 void outputfunc4(vector<person>v) {
     cout << "outputfunc4*********" << endl;
     vector<person>::iterator pbegin = v.begin();
     // vector<person>::iterator pend = v.end();
    // while (pbegin != pend){……}
     while (pbegin != v.end() ){
         cout <<"name:" << pbegin->name << endl;
         cout << "age:" << pbegin->age << endl;
         pbegin++;
     }     
 }


void test01() {

    vector<person>v;//init vector

    person p1("小米", 6);//create objects
    person p2("小紅", 18);
    person p3("小江", 15);

    v.push_back(p1);//input elements
    v.push_back(p2);
    v.push_back(p3);
    outputfunc1(v);
    outputfunc2(v);
    outputfunc3(v);
    outputfunc4(v);

}

int main() {

    test01();
    system("pause");
    return 0;

}