C ++例程将所有short放入一个集合 [英] C++ routine to place all short into a set
问题描述
这应该是可能的,因为 short int
的数量小于 max_size()
std :: set< short int>
:
It should be possible, since the number of short int
s is less than the max_size()
of an std::set<short int>
:
#include <iostream>
#include <set>
#include <limits.h>
#include <math.h>
int main()
{
std::set<short int> mySet;
std::cout << "Max size of mySet is " << mySet.max_size() << std::endl;
std::cout << "Number of short ints is " << pow(2.0, double(sizeof(short int) * CHAR_BIT));
return 0;
}
输出
Max size of mySet is 4294967295
Number of short ints is 65536
$ b b
现在,我想做的是将所有 short int
放入一个集合,这意味着我需要一个例程来遍历所有 short int
s。如果可能,我想要一个通用例程来迭代给定类型的所有元素。任何人都有一些洞察力?
Now, what I'd like to do is place all short int
s into a set, meaning I need a routine to iterate over all short int
s. If possible, I would like a general routine for iterating over all elements of a given type. Anyone have some insight?
推荐答案
编辑:使用模板函数接受其他小数类型。
with a template function to accept other decimal types.
template<typename T>
std::unique_ptr<set<T>> CreateSet()
{
unique_ptr<std::set<T>> mySet(new std::set<T>());
for( T i = std::numeric_limits<T>::min(); i < std::numeric_limits<T>::max(); i++ )
{
mySet->insert( i );
}
mySet->insert(std::numeric_limits<T>::max());
//std::cout << mySet->size();
return mySet;
}
int main() {
auto s = CreateSet<short int>();
// ...
return 0;
}
感谢评论者修复
注意:不清楚为什么你会想要这个,甚至为什么你想使用一个集合(而不是一个向量),当唯一性由建设保证。
Note: it is unclear why you would want this, or even why you want to use a set (and not a vector) when uniqueness is guaranteed by construction.
这篇关于C ++例程将所有short放入一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!