温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么使用gsl::index

发布时间:2021-11-25 16:21:58 来源:亿速云 阅读:302 作者:iii 栏目:大数据

这篇文章主要介绍“C++怎么使用gsl::index”,在日常操作中,相信很多人在C++怎么使用gsl::index问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++怎么使用gsl::index”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

ES.107:不要使用无符号数下标,使用gsl::index更好

Reason(原因)

为了避免有符号数/无符号数混用带来的问题。有利实现更好的优化和错误检查。避免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(注意)

内置数组使用有符号数下标。标准库容器使用无符号数下标。因此不存在完美、完全兼容的解决方案(除非将来某一天标准库容器转而使用有符号数下标)。考虑到使用无符号数或者有符号数/无符号数混合可能带来的问题,较好的选择是赋予(有符号)整数足够大的空间,这一点可以通过使用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.

  • (为了避免误检出)如果一个操作数是sizeof或者container.size()而另一个操作数是ptrdiff_t,不要标记有符号数/无符号数混合的比较操作。

到此,关于“C++怎么使用gsl::index”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI