小编mon*_*olo的帖子

同类容器,其类型仅在运行时已知

我有一个单一类型的集合,其类型只在运行时知道.一旦定义了类型,它就永远不会改变.我目前正在向量中存储指向对象的指针,如下所示:

std::vector<Animal*> v;
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以将实例存储在连续的内存中.我的目的是编写一个更加缓存友好的代码并更快地迭代容器.

我可以为每个向量的元素使用boost :: variant,例如,

std::vector<boost::variant< Cat, Dog > >
Run Code Online (Sandbox Code Playgroud)

但如果sizeof(Dog)sizeof(Cat)那时大得多,那么在对象属于类型的情况下会浪费内存Cat.

我也可以使用Variant的容器:

boost::variant< std::vector<Cat>, std::vector<Dog> >
Run Code Online (Sandbox Code Playgroud)

但是我不知道在这种情况下迭代器会是多少,如果它们会引入更多的开销.

"指针矢量接近"是我们能做的最好的吗?

更多信息:对象的大小在50到250个字节之间,容器长度在10到1M之间,我必须在容器上迭代一百万次.

谢谢.

编辑:我在这里发现了一个类似的问题(也有很好的建议): 如何用C++编写缓存友好的多态代码?

c++ optimization containers

7
推荐指数
1
解决办法
1117
查看次数

c ++递归类型特征

我正在尝试实现一个模板类(此处名为Get <>),给定结构H,如果不存在,则类型Get<>H自身Get<H>::type H,H::der否则为.我无法理解以下代码有什么问题:

#include <iostream>
#include <typeinfo>
using namespace std;

template<class U, class V = void>
struct Get
{
  static const char id = 'A';
  typedef U type;
};

template<class U>
struct Get<U,typename U::der>
{
  static const char id = 'B';
  typedef typename Get<typename U::der>::type type;
};

struct H1
{ };
struct H2
{ typedef double der; };
struct H3
{ typedef void der; };
struct H4
{ typedef H2 der; }; …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-traits

5
推荐指数
1
解决办法
399
查看次数

C++11 丢弃 PRNG 序列中的数字

我正在尝试使用该函数discard来跳过随机数序列中的数字。这是我的尝试:

#include <random>
#include <iostream>

using namespace std;

int main ()
{
  unsigned seed = 1;
  uniform_real_distribution<> dis(0,10);
  mt19937 gen (seed);
  cout << dis(gen) << endl;
  //gen.discard(1); // supposed to be the same of `dis(gen)`?
  cout << dis(gen) << endl;
  cout << dis(gen) << endl;
}
Run Code Online (Sandbox Code Playgroud)

这段代码的输出是

9.97185
9.32557
1.28124
Run Code Online (Sandbox Code Playgroud)

如果我取消注释该行,gen.discard(1)我会得到

9.97185
0.00114381
3.02333
Run Code Online (Sandbox Code Playgroud)

但我预计前两个数字是9.971851.28124,因为该数字9.32557将被跳过。

:如何discard正确使用,或者有没有与我想要的效果相同的替代解决方案?我可以简单地使用dis(gen),但是还有其他方法吗?

c++ random c++11

3
推荐指数
1
解决办法
307
查看次数

标签 统计

c++ ×3

c++11 ×1

containers ×1

optimization ×1

random ×1

templates ×1

type-traits ×1