編寫一個pair存入一組string,int類型數據,並保持到vector中

例題:編寫一個pair存入一組string,int類型數據,並保持到vector中

#include<iostream>
#include<utility>
#include<vector>


using namespace std;


int main()
{
        vector < pair<string,int> > ivec;               //create a vector
        vector < pair<string,int> >::iterator It;       //create a iterator
        string first;
        int last;
        while(cin >> first >> last)
        {
                if(first=="exit"&&last==0)                          //the exit condition
                        break;
                ivec.push_back(make_pair(first,last));  //make_pair can create a new pair
        }
        It=ivec.begin();
        cout<<endl;
        cout<<"the vector content is: "<<endl;
        while(It!=ivec.end())
        {
                cout<<(*It).first<<"---"<<(*It).second<<endl;
                It++;
        }
        getchar();
        return 0;
}

執行結果:

hello 1
hello 2
hello 3
hello 4
exit 5
exit 0


the vector content is: 
hello---1
hello---2
hello---3
hello---4
exit---5


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章