需要二维对象数组,可能是这样的:
myContainer<myObject*> *a = new myArray<myObject*>( 20, 20 ); // passing int's as width & height
稍后访问值将使用以下方法完成:
mylist<myObject*> getRow( int );
mylist<myObject*> getColumn( int );
mylist<myObject*> getDiagonalRow( int );
这些的实现可能是这样的:
myList<myObject*> myContainer::getRow( int a ){
if( a < 0 && a>=this->height )
return;
myList<myObject*> hlp;
for( int i=0; i<this->width; i++)
hlp.append( this->arr[a][i] );
return hlp; // returns a copy. Could also be a pointer if created with new.
}
其他方法可以遵循类似的路线,即。创建一个列表对象并用请求的内容填充它。
我的问题:谁能想出优雅的方法来创建我在这里描述的容器类。例如,这可以避免创建和填充列表对象,但仍保持抽象和/或可用性。或者,如果我在 STL 等中遗漏了类似这样的内容,请提出建议。
最佳答案
STL 有 valarray 容器,可以使用切片将其视为行和列,但您必须手动完成或将其包装到包装类中。此外,切片代表 valarray 的值(它们不是拷贝),但它被设计为与数字一起使用并进行了一些优化,它没有任何迭代器并且不能增长。它不遵循通常的 STL 容器概念。但如果您不能使用 boost,它仍然可以用作快速而肮脏的解决方法。
std::valarray<float> array(16);
// we can view it as a 4x4 matrix.
// this represents the first line
array[std::slice(0,4,1)];
// and the second column
array[std::slice(1,4,4)];
// you cannot use the sliced array directly. they don't
// have operator[], but they have operator=(valarray), and
// valarray has a constructor that takes sliced arrays as input.
关于c++ - 高效/优雅的二维容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5231781/