如图,数字代表不同的字符串,我想知道用什么方法可遍历以做到找到每一列中最长的字符串的长度。 注意,图只是一种情况,已知字符串数组的行数和每一行对应的列数
1 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
// Q695423.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "stdlib.h" #include "string.h" #include <iostream> using namespace std; struct MyArr { int len; char ** arr; MyArr(int n, char * _arr[]) { n = n / (sizeof(char *)); arr = new char *[n]; len = n; for (int i = 0; i < n; i++) arr[i] = _arr[i]; } ~MyArr() { delete[] arr; } }; class ExpendCol { private: int _len; int _alen; int * _pa; void expend(int a) { int * pp = _pa; _pa = new int[a]; memset(_pa, 0, sizeof(int) * a); memcpy(_pa, pp, sizeof(int) * _len); delete[] pp; _alen = a; } public: ExpendCol() { _alen = 1; _pa = new int[_alen]; _len = 0; } ~ExpendCol() { delete[] _pa; } void set(int index, int value) { while (index >= _alen) { expend(_alen * 2); } if (_len <= index) _len = index + 1; _pa[index] = value; } int get(int index) { if (index >= _len) return 0; return _pa[index]; } int length() { return _len; } }; int _tmain(int argc, _TCHAR* argv[]) { char * s1 = "file"; char * s2 = "edit"; char * s3 = "view"; char * s4 = "project"; char * s5 = "build"; char * s6 = "debug"; char * s7 = "team"; char * s8 = "data"; char * s9 = "tools"; char * s10 = "architecture"; char * a1[] = { s1, s2, s3 }; char * a2[] = { s4, s5, s6, s7 }; char * a3[] = { s8, s9 }; char * a4[] = { s10 }; MyArr arr[] = { MyArr(sizeof(a1), a1), MyArr(sizeof(a2), a2), MyArr(sizeof(a3), a3), MyArr(sizeof(a4), a4) }; ExpendCol r; for (int i = 0; i < sizeof(arr) / sizeof(MyArr); i++) { for (int j = 0; j < arr[i].len; j++) { int slen = strlen(arr[i].arr[j]); if (r.get(j) < slen) r.set(j, slen); } } for (int i = 0; i < r.length(); i++) { cout << "col" << i << ":" << r.get(i) << endl; } return 0; }
- 1 回答
- 0 关注
- 840 浏览
添加回答
举报
0/150
提交
取消