溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么使用gsl::index

發(fā)布時間:2021-11-25 16:21:58 來源:億速云 閱讀:319 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“C++怎么使用gsl::index”,在日常操作中,相信很多人在C++怎么使用gsl::index問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C++怎么使用gsl::index”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

ES.107:不要使用無符號數(shù)下標,使用gsl::index更好

Reason(原因)

為了避免有符號數(shù)/無符號數(shù)混用帶來的問題。有利實現(xiàn)更好的優(yōu)化和錯誤檢查。避免auto和int類型帶來的陷阱。

Example, bad(反面示例)

vector<int> vec = /*...*/;

for (int i = 0; i < vec.size(); i += 2)                    // may not be big enough
   cout << vec[i] << '\n';
for (unsigned i = 0; i < vec.size(); i += 2)               // risk wraparound
   cout << vec[i] << '\n';
for (auto i = 0; i < vec.size(); i += 2)                   // may not be big enough
   cout << vec[i] << '\n';
for (vector<int>::size_type i = 0; i < vec.size(); i += 2) // verbose
   cout << vec[i] << '\n';
for (auto i = vec.size()-1; i >= 0; i -= 2)                // bug
   cout << vec[i] << '\n';
for (int i = vec.size()-1; i >= 0; i -= 2)                 // may not be big enough
   cout << vec[i] << '\n';
Example, good(范例)
vector<int> vec = /*...*/;

for (gsl::index i = 0; i < vec.size(); i += 2)             // ok
   cout << vec[i] << '\n';
for (gsl::index i = vec.size()-1; i >= 0; i -= 2)          // ok
   cout << vec[i] << '\n';
Note(注意)

內置數(shù)組使用有符號數(shù)下標。標準庫容器使用無符號數(shù)下標。因此不存在完美、完全兼容的解決方案(除非將來某一天標準庫容器轉而使用有符號數(shù)下標)??紤]到使用無符號數(shù)或者有符號數(shù)/無符號數(shù)混合可能帶來的問題,較好的選擇是賦予(有符號)整數(shù)足夠大的空間,這一點可以通過使用gsl::index保證。

Example(示例)

template<typename T>
struct My_container {
public:
   // ...
   T& operator[](gsl::index i);    // not unsigned
   // ...
};
Alternatives(其他選項)

Alternatives for users

利用者角度的其他選項

  • use algorithms

  • 使用算法

  • use range-for

  • 使用范圍for

  • use iterators/pointers

  • 使用指針和迭代器


Enforcement(實施建議)

  • Very tricky as long as the standard-library containers get it wrong.

  • 如果標準庫容器出問題了,很難檢出。

  • (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is sizeof or a call to container .size() and the other is ptrdiff_t.

  • (為了避免誤檢出)如果一個操作數(shù)是sizeof或者container.size()而另一個操作數(shù)是ptrdiff_t,不要標記有符號數(shù)/無符號數(shù)混合的比較操作。

到此,關于“C++怎么使用gsl::index”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

c++
AI