为什么 break 语句会终止程序?

Why does break statement terminate program?

我有一个 break 语句退出循环:

while (cin >> text){
        if (text == "break"){

            break;

        };

        cout << text << endl;
        words.push_back(text);

    }

问题是程序在

之后就停止了

Exit code: 0 (normal program termination).

这是我的完整程序:

// Example program
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

int main()
{

    string text;
    vector<string> words;
    vector<int> indices;
    vector<int> indices_sorted;
    vector<string> words_sorted;


    cout << "type in you're desired Text: ";
    while (cin >> text){
        if (text == "break"){

            break;

        };

        cout << text << endl;
        words.push_back(text);

    }

    int size = words.size();

    for (int i =0; i < size; i++){

        indices_sorted.push_back(words[i].size());


    }

    indices = indices_sorted;
    sort(indices_sorted.end(),indices_sorted.begin());
    cout << "you typed: " << words.size() << " words!";
    int counter = 0 ;
    for (int i =0; i < size; i++){
        while (indices[i] != indices[counter])counter++;

        words_sorted.push_back(words[counter]);
        counter = 0;

        cout << words_sorted[i]<< endl;


    }

    return 0;
}

你写了

sort(indices_sorted.end(),indices_sorted.begin());

这违反了 std::sort 的先决条件,即第二个迭代器必须通过递增从第一个迭代器到达。在您的代码中不会出现这种情况,除非 indices_sorted 为空(即 begin 等于 end),因此您正在调用未定义的行为。

你需要交换参数

sort(indices_sorted.begin(),indices_sorted.end());

然后是你的程序works