[C++-sig] Re: Howto wrap operator[]? (boost::python)
Ralf W. Grosse-Kunstleve
rwgk at yahoo.com
Sat Jun 14 05:42:16 CEST 2003
--- Mike Rovner <mike at bindkey.com> wrote:
>
> "Nicodemus" <nicodemus at globalite.com.br> wrote in message
> news:3EEA3FE1.3080601 at globalite.com.br...
>
> > template <class T>
> > void vector_setitem(std::vector<T>& v, int index, T value)
> > {
> > if (index >= 0 && index < v.size()) {
> > v[index] = value;
> > }
> > else {
> > PyErr_SetString(PyExc_IndexError, "index out of range");
> > throw_error_already_set();
> > }
> > }
>
> That will forbid very useful Python feature - negative index :(
> So better include
>
> if( index < 0 ) index+=v.size();
>
> before your if.
One more nit: replace int by long to support very large arrays.
FWIW: here is my little helper function, carefully tailored to
mirror indexing of builtin lists:
inline
std::size_t
positive_getitem_index(long i, std::size_t size)
{
if (i >= 0) {
if (i >= size) raise_index_error();
return i;
}
if (-i > size) raise_index_error();
return size + i;
}
The size parameter is the size of the indexed object.
raise_index_error() is another tiny helper equivalent to the
two lines for rasing the exception in the quoted section above.
Ralf
__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com
More information about the Cplusplus-sig
mailing list