c – 计算对象数组的元素(大小)
发布时间:2020-12-16 06:57:10 所属栏目:百科 来源:网络整理
导读:我正在学习/练习对象数组和指向对象的数组,我对如何获得动态数组大小非常困惑. 我有这个: private: Client ** arr_client;public: static string members []; 然后使用以下静态字符串数组成员的标记化数据填充数组arr_client: static string members[] = {
我正在学习/练习对象数组和指向对象的数组,我对如何获得动态数组大小非常困惑.
我有这个: private: Client ** arr_client; public: static string members []; 然后使用以下静态字符串数组成员的标记化数据填充数组arr_client: static string members[] = {"Jhon Perez 623 22 12 1998","Louis Smith 199 02 12 1988","Daniel Martinez 106 02 01 2010"}; void load(void){ arr_client = new Client * [(sizeof(members)/sizeof(string))*sizeof(Client)]; for (i = 0; i < (sizeof(members)/sizeof(string)); i++){ istringstream stream(members[i],ios_base::in); stream >> name; stream >> lastname; stream >> aux; id = atoi(aux.c_str()); stream >> date; date.append(" "); stream >> aux; date.append(aux); date.append(" "); stream >> aux; date.append(aux); arr_client[i] = new Client(name,lastname,id,date); } } 现在,在对象数组已满后,我想循环遍历arr_client但我似乎无法找到实现它的方法. 我应该使用: for (int i =0; i < (sizeof(**arr_client)/sizeof(client)); i++) 或取以前的cal为大小,并执行: for (int i =0; i < (sizeof(members)/sizeof(string)); i++) 并完成它?对我来说看起来并不那么有用……但是我又很新. 我也有几个问题: 如果我不知道动态合成对象数组的大小怎么办?就像在这种情况下,我建立在已知大小的阵列上. 如何计算其中有多少元素,以便我可以遍历它? 我可以为arr_client使用std :: iterator吗? 任何提示将非常感激=) 并且……是的,我确实知道< vector>了解这些情况是优点,但从不伤害. 解决方法
首先,我赞赏你在采用像矢量这样的高级工具之前尝试学习基础知识.
没有干净可靠的方法来做你要求的事情.人们通常会在单独的变量中记住数组的大小,如下所示: unsigned int num_strings=3; static string members[num_strings]; 如果您确实想在运行时确定数组的大小,可以使用模板: template<typename T,size_t N> size_t arraySize( T(&)[N] ) { return(N); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |