2011-10-01 63 views
2

我正试图对我设计的库做一个防水接口。用户需要输入二维数据,因此我认为类似于std::transform的迭代器界面将是透明的。 但是,我不确定如何异常处理滥用迭代器。异常处理迭代器接口

我的界面中,就像这样(我可以改变界面,如果有更好的一个):

template<typename InputItrX, typename InputItrY> 
set_data(InputItrX beginX, InputItrX endX, InputItrY beginY) 
{ 
    //What exception handling should I do here? 
    size_t array_size = endX-beginX; //get the size of the xarray. 
    my_xVector.resize(array_size); //resize my internal container 
    my_yVector.resize(array_size); // ..and for the ydata. 
    std::copy(beginX, endX, my_xVector.begin());    //copy X 
    std::copy(beginY, beginY+array_size, my_yVector.begin()); //copy Y 
} 

例如,我的计划变得不确定,如果用户得到糊涂了接口,并写入

set_data(xdata.begin(), ydata.begin(), xdata.end()); 

或可能它们的xdata有20个元素,但它们的ydata没有。

是否有可能检查我的图书馆界面中的这种错误?

回答

1

我不会为该方法添加任何检查,但记录异常规范依赖于使用的迭代器。因此,如果用户不关心性能损失或未检查的迭代器并获得最佳性能,那么用户可以使用选中的迭代器。我认为大多数STL迭代器的实现都声明检查迭代器的不兼容性。这些错误不需要在发布模式下检查,因为它们是程序员的错误。

size_t array_size = endX-beginX; //get the size of the xarray. 
my_xVector.resize(array_size); //resize my internal container 
my_yVector.resize(array_size); // ..and for the ydata. 

这使得你的方法与没有-operator的迭代器不兼容!它只能用于随机访问迭代器。你应该把这个提取到一个resize_vectors模板,该模板可以用于随机访问迭代器,但不会为其他迭代器调整大小。在std::copy中,您必须使用插入器迭代器来调整矢量的大小,插入矢量时没有足够的容量。

+0

+1,我没有想过随机存取限制。 – Tom

+0

为了完整性:随机访问迭代器检查在这里解决:http://stackoverflow.com/q/4307271/498253 – Tom