C ++自我执行标准:size_t [英] C++ self-enforcing a standard: size_t

查看:129
本文介绍了C ++自我执行标准:size_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,
在处理数组或其他大型数据结构时,我通常会在我通常使用整数的地方强迫自己开始使用size_t(或unsigned longs?)会对我有好处吗?

Simple question, Would it be good for me to force myself to start using size_t (or unsigned longs?) in places where I would normally use ints when dealing with arrays or other large datastructures?

假设你有一个向量指针:

Say you have a vector pointer:

auto myVectorPtr = myVector;

您不知道,此向量的大小大于:

Unknown to you, the size of this vector is larger than:

std::numeric_limits<int>::max();

你有一个循环:

for(int i = 0; i < myVectorPtr->size(); ++i)

使用

for(size_t i = 0; i < myVectorPtr->size(); ++i)

以避免遇到溢出?

我想我的问题是,在算术和其他常见操作中使用size_t(或unsigned longs?)是否有任何副作用?如果我开始使用size_t(或unsigned longs?)而不是经典int,我需要注意什么。

I guess my question really is, are there any side effects of using size_t (or unsigned longs?) in arithmetic and other common operations. Is there anything I need to watch out for if I started using size_t (or unsigned longs?) instead of the classic int.

推荐答案

size_t 肯定比 int 更好。最安全的做法是使用容器的实际 size_type ,例如:

size_t is certainly better than int. The safest thing to do would be to use the actual size_type of the container, e.g.:

for( typename decltype(*myVectorPtr)::size_type i = 0; i < myVectorPtr->size(); ++i )

不幸的是 auto 不能在这里使用,因为它会从 0 ,而不是来自 size()调用。

Unfortunately auto cannot be used here because it would deduce its type from 0, not from the size() call.

使用迭代器或者读取它会更好一点基于范围的接口:

It reads a bit nicer to use iterator or range-based interfaces:

for (auto iter = begin(*myVectorPtr); iter != end(*myVectorPtr); ++iter)

for (auto &&item : *myVectorPtr)

这篇关于C ++自我执行标准:size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆