VC++ 使用 typedef, Tuple, Array 来模拟一个对象的列表,并对列表进行增减、赋值和访问,

本文通过一个综合示例介绍了C++中元组(tuple)和数组(array)的应用方法,包括定义、初始化、修改及遍历操作,并展示了如何将这些数据结构应用于具体的人员记录管理场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是综合例子:


#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;
}


不多说,呈上运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值