下面是综合例子:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <tuple>
#include <iomanip>
#include <array>
using std::cout;
using std::endl;
using std::tuple;
using std::string;
using std::setw;
using std::get;
const size_t maxRecords(100);
typedef std::tuple<int,std::string,std::string,int> PeopleRecord; //使用typedef和Tuple定义对象
typedef std::array<PeopleRecord,maxRecords> Records; //定义对象数组
void listRecords(const Records& people){
const size_t ID(0), firstanme(1), secondname(2),age(3);
cout<< std::setiosflags(std::ios::left);
PeopleRecord empty;
for(auto& record:people){
if(record == empty) break; //In case array is not full
cout<<"ID:" <<setw(6) <<get<ID>(record)
<<"Name:" <<setw(25)<<(get<firstanme>(record) + " " + get<secondname>(record))
<<"Age:" <<setw(5) <<get<age>(record)
<<endl;
}
}
int main(int argc,_TCHAR* argv[])
{
Records rList = {
PeopleRecord(1001,"Arthur","Dent1",35),
PeopleRecord(1002,"Arthur","Dent2",36),
PeopleRecord(1003,"Arthur","Dent3",37),
PeopleRecord(1004,"Arthur","Dent4",38),
};
rList[4] = std::make_tuple(1005,"Harry","Potter",12); <span style="white-space:pre"> </span>//对象追加:Tuple方式
rList.at(5) = PeopleRecord(1006,"Bertie","Wooster",28);<span style="white-space:pre"> </span>//对象追加:对象方式
listRecords(rList);
cout<<endl;
rList[3] = std::make_tuple(157,"Terry","Potter",2);<span style="white-space:pre"> </span>//对象修改:Tuple方式,对象方式略
listRecords(rList);
return 0;
}
不多说,呈上运行结果: