Generic vector of vectors in C++(C++中向量的通用向量)
问题描述
在 C++ 中是否有一种好方法来实现(或伪造)通用向量向量的类型?
Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?
忽略向量向量何时是一个好主意的问题(除非有一些等效的东西总是更好).假设它确实准确地对问题建模,而矩阵不能准确地对问题建模.还假设将这些东西作为参数的模板化函数确实需要操作结构(例如调用 push_back),因此它们不能只采用支持 [][]
的泛型类型.
Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push_back), so they can't just take a generic type supporting [][]
.
我想做的是:
template<typename T>
typedef vector< vector<T> > vecvec;
vecvec<int> intSequences;
vecvec<string> stringSequences;
当然这是不可能的,因为 typedef 不能被模板化.
but of course that's not possible, since typedef can't be templated.
#define vecvec(T) vector< vector<T> >
很接近,并且可以避免在对 vecvecs 进行操作的每个模板化函数中重复类型,但不会受到大多数 C++ 程序员的欢迎.
is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers.
推荐答案
您想要模板类型定义.目前的 C++ 尚不支持 .解决方法是做
You want to have template-typedefs. That is not yet supported in the current C++. A workaround is to do
template<typename T>
struct vecvec {
typedef std::vector< std::vector<T> > type;
};
int main() {
vecvec<int>::type intSequences;
vecvec<std::string>::type stringSequences;
}
在下一个 C++(由于 2010 年称为 c++0x、c++1x)中,这将是可能的:
In the next C++ (called c++0x, c++1x due to 2010), this would be possible:
template<typename T>
using vecvec = std::vector< std::vector<T> >;
这篇关于C++中向量的通用向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中向量的通用向量


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01