C++ INT到类的映射(模板)
我想写一些使用模板将int映射到某物的类。 我通常考虑两种选择:C++ INT到类的映射(模板),c++,stl,map,C++,Stl,Map,我想写一些使用模板将int映射到某物的类。 我通常考虑两种选择: 1. unsigned int -> double (scalar) 2. unsigned int -> double[N] (vector of length N; N is the same for each int) 我在附近写了一节课 template <class T> class int2type_storage { public: ....
1. unsigned int -> double (scalar)
2. unsigned int -> double[N] (vector of length N; N is the same for each int)
我在附近写了一节课
template <class T>
class int2type_storage {
public:
....
private:
typename std::map<unsigned int,T> map_;
}
模板
类int2type_存储{
公众:
....
私人:
typename std::映射映射;
}
对于第一种情况,用法很简单:
int2type_storage<double> map1;
int2type\u存储映射1;
问题是,第二种情况下最有效的方式/目标是什么?
我想做些类似的事情
int2type_storage< std::vector<double> >
int2type\u存储
但我有一种感觉,这将是次优的。另一种选择是存储指针
int2type_storage< double* >
int2type\u存储
但是我有一个问题,我应该为map类之外的N个元素分配内存,并注意以后释放它
EDIT1:谢谢你们的回答,很抱歉我不能把两个答案标为正确
编辑2:
我已经实现了所有功能,但我的链接器找不到函数:
undefined reference to `int2type_storage<std::tr1::array<double, 4ul> >::init(int, int)'
int2type_storage::init(int,int)的未定义引用
.h:
模板
类int2type_存储{
公众:
int2type_storage(){};
~int2type_storage(){};
void init(常数整数编号,常数整数索引);
...
私人:
国际货币指数;
typename std::map::迭代器迭代器;
typename std::vector map\u vector\u;
boolzero_初始化;
};
.cpp:
模板
void int2type_存储::init(const int length,const int max_index){
映射向量大小(长度);
}
用法:
int2type_storage< std::tr1::array<double, 4> > w_map_;
int2type\u存储w\u映射;
怎么了?如果编译时已知
N
,则可以使用std::array
:
如果你有C++11,
std::array
是最好的,还有Boost.array
如果你没有,那么你可以写一些类似的东西:
template <size_t N>
struct Doubles {
double data[N];
};
模板
双重结构{
双数据[N];
};
然后直接使用.data
访问它,或者添加任意数量的成员函数和运算符重载。如果您添加正确的,那么最终您将拥有std::array
double*
的主要合理用途是复制映射(或者有多个映射),并且希望它们引用相同的数据。但是,正如您已经知道的,它创建了一个资源管理问题,因此您可以考虑<代码> SydDyLaxs/Cuff>。你也可以考虑不共享数据。
还有一种可能的特殊情况,在C++03中,元素被复制到容器中,而在C++11中,在某些情况下,将元素移动到容器中可能会提高效率。但是数组(包括
std::array
和上面的my类)不能有效地移动。如果N
很大,并且存在大量复制,那么可以有效移动的东西可能会工作得更好,所以,你可以再考虑<代码> STD::向量。我怀疑你是否需要切换向量到指针来增加性能。我不使用向量的唯一原因是它们没有大小N。但是我不会担心在绘制之前的性能考虑。包装器的原因是一些更相关的函数。获取/设置与问题无关的元素、查找等。我没有C++11,我在Ubuntu上,用mpic++编译代码。编译器还抱怨数组不是std的成员(我包括了
)@Denis那么你应该使用std::tr1::array
作为第一部分,但你不能做第二部分(但看起来你根本不需要它)。我试图使用你的解决方案,但无法让它工作。你能看一下吗?@Denis你必须在头中实现模板代码,或者在头中包含一个文件。因此,将init
函数定义放在头文件中。
int2type_storage< std::tr1::array<double, 4> > w_map_;
int2type_storage< std::array<double, N> >
template <typename T, int N>
using int2type_storage = std::map<unsigned int, std::array<T,N>>;
template <size_t N>
struct Doubles {
double data[N];
};