为什么我的代码在第一个for循环后停止运行?
C++: Why does my code stop running after the first for loop?
#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等,所以我想弄清楚这个问题。
我想要完成的是打印出数组,然后按字母顺序打印出来,然后找到重复项并删除并再次打印出来。最后,找出数组中每个单词的长度并打印出来。
正如评论中提到的,您第一次使用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风格的数组,这也将继续工作。
相关文章:
- 循环无限运行C++解决骑士之旅问题
- 我的代码运行良好,但在游戏循环中中断
- 如何根据用户在C++中的输入运行不同数量的 for 循环
- 我可以根据用户输入在运行时生成"循环"吗?
- 重新启动后,线程无法在 while 循环中再次运行
- 运行无限循环的最小二叉树问题
- 目标C++,如何在后台线程中使用运行循环?
- 如何在指定的时间内运行循环
- 苹果运行循环的回调方法
- 我怎样才能一直运行循环,直到按下键 (C++)
- 如何在C++中每次运行循环时将变量递增1`
- 如何在第一次运行循环时忽略代码的特定部分
- 如何在每次运行循环时更改for循环中的对象
- 应用程序在访问主运行循环时崩溃 (SIGABRT)
- osX :运行循环选项(创建事件点击时)
- 线程如何运行循环直到连接
- 在指定时间运行c++循环
- 在运行循环外声明、分配和释放线程局部指针变量
- 这是在c++中运行循环的有效方式吗?
- 如何在qt中使用gui对象名运行循环