![](/img/trans.png)
[英]Why doesn't this break terminate the program, but instead proceeds to the next operation?
[英]Why does break statement terminate program?
我有一個 break 語句來退出循環:
while (cin >> text){
if (text == "break"){
break;
};
cout << text << endl;
words.push_back(text);
}
問題是程序隨后停止
退出代碼:0(正常程序終止)。
這是我的完整程序:
// 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
),因此您正在調用未定義的行為。
您需要更換 arguments
sort(indices_sorted.begin(),indices_sorted.end());
然后你的程序工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.