How to emulate back() method for array?

95 views Asked by At

There is no back() method in boost::numeric::ublas::vector, is it possible to emulate it in user code with preprocessor macro defining somehow array_name[array_name.size()-1]?

array_name[i].rbegin()->operator[] (i) = 1.0 or array_name[i][array_name[i].size()-1][i] = 1.0 hard to read, array_name[i].back()[i] = 1.0 easy to read, that why i thinking to emulate back() method.

2

There are 2 answers

5
cdonat On

Consider to use std::array<> instead of C-arrays. Then you'll have array_name.back() as well. Note, that std::array<> comes with no overhead to C-arrays.

If it really has to be C-arrays with static size, then

array_name[(sizeof(array_name) / sizeof(array_name[0])) - 1]

should do the trick, though I have not yet tested. Dynamically sized arrays (those allocated with new or malloc()) don't carry any length information. You can not determine their last element, without having stored the length somewhere else.

BTW.: boost::numeric::ublas::vector does have size(), so you can do

vector_name[vector_name.size() - 1]

It also has reverse iterators. You can do

*(vector_name.rbegin())

to get the value of the last element.

0
Brandlingo On

What you want is a free standing function which supplies the syntactic sugar you are asking for:

template <typename C>
typename C::const_reference back(const C & container)
{
    return *container.rbegin();
}

This will work for all classes with a rbegin() method and const_reference nested type. Add a second overload for non-const references if needed.

See this live on Coliru