用于数组的C++模板,并了解它们的大小
C++ template for arrays and knowing their size
我有一堆结构,比如:
struct A { ... }
struct B { ... }
struct C { ... }
我想设计一个函数,它可以接受这些结构的数组,并遍历数组的每个元素,然后调用另一个函数:
template <typename T>
ostream& process(ostream& os, const T* array) {
// output each element of array to os (but how do we know the length?)
}
A a_array[10];
process(a_array);
由于过程函数实际上是运算符<lt;()(我只是把流程用于演示目的)
更新:我不能在这里使用任何std容器。不幸的是,它必须是一个数组!
数组到指针的衰减非常非常糟糕。
幸运的是,C++有数组引用,它们知道它们的大小。
template<typename T, size_t N> ostream& process(ostream& os, const T (&arr)[N]) {
// use N
}
您可以使用std::vector<T>
而不是简单的数组。
template <typename T>
ostream& process(ostream& os, const std::vector<T> &array) {
for(std::vector<T>::const_iterator iterator = array.begin(); iterator != array.end(); ++iterator)
{
//...
}
}
或者您可以使用std::array方法(如果您的编译器支持它并且N是常量)。
template <typename T, int N>
ostream& process(ostream& os, const std::array<T, N> &array) {
for(std::array<T, N>::const_iterator iterator = array.begin(); iterator != array.end(); ++iterator)
{
//...
}
}
// Usage:
array<int, 10> test;
process(..., test);
您需要对数组使用以下格式:
template <typename T, size_t N>
void foo(const T (&arr)[N]) {
...
}
否则,大小信息将丢失。
或者,一个简单的模板边界检查数组。
template< typename T, unsigned int Size >
class Array
{
public:
T& operator[]( unsigned int index )
{
assert( index < Size );
return mElements[ index ];
}
const T& operator[]( unsigned int index ) const
{
assert( index < Size );
return mElements[ index ];
}
unsigned int Capacity() const
{
return Size;
}
private:
T mElements[ Size ];
};
然后
template< typename T, unsigned int Size >
void Process( Array< T, Size >& array )
{
for( unsigned int i = 0; i < Size; ++i )
{
//use array[i]
}
}
把它绑在一起
Array< int, 10 > array;
Process( array );
这有点像你自己的解决方案,但它可能大致等同于std::array或boost
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 了解字符数组初始化和数据存储
- 问题是关于C 的数组,以便在编程主题中有更多的了解
- 通过动态内存分配了解2D数组
- 了解 C++ 中数组和指针的差异/相似之处
- 不了解什么是内部数组
- 了解递归函数中的数组和指针
- 了解字符数组内存分配
- 了解 2-D 数组的卡达内算法
- 用于数组的C++模板,并了解它们的大小
- 了解在将数组传递给没有大小的函数时丢失的信息
- 不了解示例中的行为 - strcpy() 和返回本地数组地址的函数
- 了解C++中的多维字符串数组
- 了解顶点数组对象(glGenVertexArrays)