什么时候应该使用向量< int> :: size_type而不是size_t? [英] When should I use vector<int>::size_type instead of size_t?

查看:182
本文介绍了什么时候应该使用向量< int> :: size_type而不是size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题中,我看到以下内容:

In this question I see following:

for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix) {
    ivec[ix] = 0;
}



我理解为什么 int 这里不使用,但为什么不使用 size_t

I understand that why int is not used here, but why not just use size_t?

在什么情况下,我应该使用 vector< int> :: size_type ,而不是 c> c>

Under what circumstances I should use vector<int>::size_type instead of size_t?

推荐答案

c>在模板中。虽然 std :: vector< T> :: size-type 通常是 size_t some_other_container< ; T> :: size_type 可能是一些其他类型。用户被允许添加到 std 命名空间的少数事情之一是某些用户定义类型的现有模板的特殊化。因此, std :: vector< T> :: size_type 对于一些oddball T 实际上除了 size_t 之外的一些类型,即使在标准库中定义的基本模板可能总是使用 size_t

The primary time to use size_type is in a template. Although std::vector<T>::size-type is usually size_t, some_other_container<T>::size_type might be some other type instead. One of the few things a user is allowed to add to the std namespace is a specialization of an existing template for some user defined type. Therefore, std::vector<T>::size_type for some oddball T could actually be some type other than size_t, even though the base template defined in the standard library probably always uses size_t.

因此,如果您想为使用该容器的模板中的特定容器使用正确的类型,则需要使用 container :: size_type 而不是只是假设 size_t

Therefore, if you want to use the correct type for a specific container inside a template that works with that container, you want to use container::size_type instead of just assuming size_t.

很少直接使用容器。相反,它通常应该使用迭代器,所以代替 container< T> :: size_type ,它通常会使用 std :: iterator_traits& WhateverIterator> :: difference_type

Note, however, that generic code should rarely work directly with a container. Instead, it should typically work with iterators, so instead of container<T>::size_type, it would typically use something like std::iterator_traits<WhateverIterator>::difference_type instead.

这篇关于什么时候应该使用向量&lt; int&gt; :: size_type而不是size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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