为什么我的代码在第一个for循环后停止运行?

C++: Why does my code stop running after the first for loop?

本文关键字:运行 循环 for 我的 代码 第一个 为什么      更新时间:2023-10-16
#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风格的数组,这也将继续工作。