【问题标题】:C++ routine to place all short into a setC ++例程将所有short放入一个集合中
【发布时间】:2014-05-29 16:13:25
【问题描述】:

应该有可能,因为short ints 的数量少于std::set<short int>max_size()

#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

现在,我想做的是将所有short ints 放入一个集合中,这意味着我需要一个例程来迭代所有short ints。如果可能的话,我想要一个通用的例程来迭代给定类型的所有元素。有人有一些见识吗?

【问题讨论】:

  • 为什么需要这个?我的意思是,它有什么目的?
  • 因此循环 0 - 65535 并将每个值添加到您的集合中。
  • 遍历所有短整数,将每个短整数插入您的集合。
  • std::numeric_limits 为您提供该类型的最低和最高可能值;从那里开始,这是一个微不足道的循环。
  • @DonaldKnuth:如果你想让别人免费为你做这件事,它需要有一个目的。此外,冒充我们领域的名人也是不受欢迎的。

标签: c++


【解决方案1】:

只是为了好玩:

template <typename T>
void fill_all_values( std::set<T> &s ) {
    T t = T();
    do s.insert( t++ ); while ( t != T() );
}

一个更有趣的解决方案:

template <typename T>
void fill_all_values_2( std::set<T> &s ) {
    typedef std::set<T>::size_type size_type;
    size_type t_max = (size_type( 1 ) << (CHAR_BIT*sizeof(T))) - 1;
    for ( size_type i = 0; i < t_max; ++i )
        s.insert( *reinterpret_cast<T*>(&i) );
    s.insert( *reinterpret_cast<T*>(&t_max) );
}

【讨论】:

  • 说实话,这个问题我也不清楚。您认为它应该适用于哪些类型?
【解决方案2】:

编辑:用模板函数接受其他十进制类型。

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;
}

感谢评论者的修复

注意:不清楚为什么要这样做,甚至在构造保证唯一性的情况下为什么要使用集合(而不是向量)。

【讨论】:

  • 您的集合将缺少一个值。
  • 你需要谁在你的循环中做演员?
  • 现在您的循环不会终止。这是你可能不想要的地方auto
  • 如果你要为它创建一个函数,也许你应该从函数中返回一些东西?
  • 已编辑,但仍然不知道 OP 想用它做什么。
【解决方案3】:

我相信您的目标可以通过使用如下循环来实现。

for( int i = 0; i < 65536; i++ )
{
  mySet.insert( (short int)i );
}

应使用实际迭代的不同类型以避免溢出。但是,我完全支持上面的 cmets;你为什么需要这样一套?我强烈建议采用不同的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2015-09-25
    • 1970-01-01
    • 2011-01-23
    • 2016-12-25
    • 2016-11-03
    相关资源
    最近更新 更多