在哪里可以查找size_type的定义在C ++ STL中的向量? [英] Where can I look up the definition of size_type for vectors in the C++ STL?
问题描述
将向量的 size()
的结果转换为 unsigned int
似乎是安全的。我怎么可以确定,但?我的文档不清楚如何定义 size_type
。
今天?
现在的最佳解决方案是使用:
std :: vector< T> :: size_type
其中T是您的类型。例如:
std :: vector< std :: string> :: size_type i;
std :: vector< int> :: size_type j;
std :: vector< std :: vector< double> > :: size_type k;
(使用typedef可以帮助您更好地阅读)
$
C ++ 0x?
b
当编译器能够找到变量的类型时,你可以使用auto关键字。例如:
void doSomething(const std :: vector< double>& p_aData)
{
std :: vector< double> :: size_type i = p_aData.size(); // Old / Current way
auto j = p_aData.size(); // New C ++ 0x way,definition
decltype(p_aData.size())k; // New C ++ 0x way,declaration
}
Edit:Question from JF
如果他需要将容器的大小传递给一些现有的代码, int? - JF
这是使用STL的常见问题:一些工作。
第一个解决方案是设计代码以始终使用STL类型。例如:
typedef std :: vector< int> :: size_type VIntSize;
VIntSize getIndexOfSomeItem(const std :: vector< int> p_aInt)
{
return / *找到的值或某种std :: npos * /
}
第二个是自己进行转换,使用static_cast断言如果值超出了目标类型的边界(有时,我看到代码使用char,因为你知道,索引永远不会超过256 [我引用内存] 。
我相信这本身就是一个完整的问题。
It seems safe to cast the result of my vector's size()
function to an unsigned int
. How can I tell for sure, though? My documentation isn't clear about how size_type
is defined.
Do not assume the type of the container size (or anything else typed inside).
Today?
The best solution for now is to use:
std::vector<T>::size_type
Where T is your type. For example:
std::vector<std::string>::size_type i ;
std::vector<int>::size_type j ;
std::vector<std::vector<double> >::size_type k ;
(Using a typedef could help make this better to read)
The same goes for iterators, and all other types "inside" STL containers.
After C++0x?
When the compiler will be able to find the type of the variable, you'll be able to use the auto keyword. For example:
void doSomething(const std::vector<double> & p_aData)
{
std::vector<double>::size_type i = p_aData.size() ; // Old/Current way
auto j = p_aData.size() ; // New C++0x way, definition
decltype(p_aData.size()) k; // New C++0x way, declaration
}
Edit: Question from JF
What if he needs to pass the size of the container to some existing code that uses, say, an unsigned int? – JF
This is a problem common to the use of the STL: You cannot do it without some work.
The first solution is to design the code to always use the STL type. For example:
typedef std::vector<int>::size_type VIntSize ;
VIntSize getIndexOfSomeItem(const std::vector<int> p_aInt)
{
return /* the found value, or some kind of std::npos */
}
The second is to make the conversion yourself, using either a static_cast, using a function that will assert if the value goes out of bounds of the destination type (sometimes, I see code using "char" because, "you know, the index will never go beyond 256" [I quote from memory]).
I believe this could be a full question in itself.
这篇关于在哪里可以查找size_type的定义在C ++ STL中的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!