這篇文章主要介紹“C++中為什么循環(huán)中盡量少用break和continue”,在日常操作中,相信很多人在C++中為什么循環(huán)中盡量少用break和continue問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++中為什么循環(huán)中盡量少用break和continue”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

10年的陽新網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。網(wǎng)絡營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整陽新建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)從事“陽新網(wǎng)站設(shè)計”,“陽新網(wǎng)站推廣”以來,每個客戶項目都認真落實執(zhí)行。
ES.77:循環(huán)中盡量少用break和continue
在不規(guī)整的循環(huán)體中,很容易忽略掉break和continue。循環(huán)中的break和switch語句中的break存在顯著的不同(同時你還可以將在循環(huán)體內(nèi)放入switch語句或者在switch語句中放入循環(huán)。)
Example(示例)
switch(x) {
case 1 :
while (/* some condition */) {
//...
break;
} //Oops! break switch or break while intended?
case 2 :
//...
break;
}Often, a loop that requires a break is a good candidate for a function (algorithm), in which case the break becomes a return.
需要break的循環(huán)通常很適合做成函數(shù)(算法),這是break可以變成return。
//Original code: break inside loop
void use1()
{
std::vector<T> vec = {/* initialized with some values */};
T value;
for (const T item : vec) {
if (/* some condition*/) {
value = item;
break;
}
}
/* then do something with value */
}
//BETTER: create a function and return inside loop
T search(const std::vector<T> &vec)
{
for (const T &item : vec) {
if (/* some condition*/) return item;
}
return T(); //default value
}
void use2()
{
std::vector<T> vec = {/* initialized with some values */};
T value = search(vec);
/* then do something with value */
}
Often, a loop that uses continue can equivalently and as clearly be expressed by an if-statement.
通常,使用continue的循環(huán)可以等價地,清晰地表示為if語句。
for (int item : vec) { //BAD
if (item%2 == 0) continue;
if (item == 5) continue;
if (item > 10) continue;
/* do something with item */
}
for (int item : vec) { //GOOD
if (item%2 != 0 && item != 5 && item <= 10) {
/* do something with item */
}
}If you really need to break out a loop, a break is typically better than alternatives such as modifying the loop variable or a goto:
如果你確實需要終端一個循環(huán),break通常會優(yōu)于修改循環(huán)變量或goto語句。
到此,關(guān)于“C++中為什么循環(huán)中盡量少用break和continue”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
分享題目:C++中為什么循環(huán)中盡量少用break和continue
當前路徑:http://chinadenli.net/article22/ggppcc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、App開發(fā)、網(wǎng)站營銷、建站公司、網(wǎng)站設(shè)計、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)