#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. */
string list[] = {"fiorello", "nonuterine", "asquint", "commodore", "semiprogressive",
"aviculturist", "brayley", "tendentious", "hungriness", "overbulkily",
"subfumigation", "praline", "fiorello", "presurvey", "unjealous",
"brayley", "unimpassionate", "welshman", "dcor", "traducianist"};
int size = sizeof(list);
for (int i = 0; i < size; i++) {
cout << list[i] << endl;
// THIS IS WHERE I REALIZE NOTHING ELSE PRINTS AFTER THIS POINT.
}
cout << endl;
int z = sizeof(list) / sizeof(list[0]);
sort(list, list + z);
for (int y = 0; y < z; y++) {
cout << list[y] << endl;
}
return 0;
}
我没有强大的C ++背景,来自HTML,CSS等,所以试图解决这个问题。
我要完成的是打印出阵列,然后按字母顺序打印出来,然后找到重复项并删除并重新打印出来。最后,找出数组中每个单词的长度并打印出来。
答案 0 :(得分:2)
正如评论中所述,您第一次使用sizeof
时出错。一个很好的解决方案是根本不使用它,而是使用标准库算法,它将通过模板推导找到大小:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string list[]={"fiorello","nonuterine","asquint","commodore","semiprogressive","aviculturist","brayley","tendentious","hungriness","overbulkily","subfumigation","praline","fiorello","presurvey","unjealous","brayley","unimpassionate","welshman","dcor","traducianist"};
// Operate on each item in list - don't need to mention count explicitly
for ( auto&& s : list )
cout << s << '\n';
cout << endl;
// Same as sort(list, list+z)
sort( begin(list), end(list) );
for ( auto&& s : list )
cout << s << '\n';
cout << endl;
}
您的评论建议您计划删除重复项,但仍希望使用C风格的数组。所以你可能会在列表计数中使用变量;你可以通过使用:
得到这个size_t count = distance( begin(list), end(list) );
而不是使用sizeof事物。除了容易出错之外,即使您稍后将代码更改为使用容器而不是C样式数组,这也会继续工作。