Reputation: 21
I use []
for accessing vectors in math code. I don't want to use at()
because I don't like exceptions. I am happy explicitly checking bounds in the code when I am not sure of my indices. So, my code is full of statements of this sort: if(n >= 0 && n < vec.size())
.
My question is, I have not found in std::vector
a call like vec.isok(n)
which directly says if yes or no an index is in bounds.
Have I overlooked it? it would make for much neater code in my case.
By the way, the explicit checking is also I think more efficient than an at()
call because typically I am using nested vector structures and when I check an index n
once, I then use n
many times inside the if
bracket, sometimes thousands of times. So, my question is, do you see a neater way of doing this without two tests in the if
. Thanks!
Upvotes: 2
Views: 585
Reputation: 16824
The easiest way:
template <typename T>
inline bool isok(const std::vector<T>& vec,
typename std::vector<T>::size_type index)
{
return index >= 0 && index < vec.size();
}
then call it as isok(vec, i)
Upvotes: 3
Reputation: 56479
Yes, std::vector
has not such a thing like std::vector::isOK(x)
. You can warp std::vector
in your SafeVector
and publish the safe interfaces to use.
Upvotes: 4
Reputation: 1145
You can have your own implementation of accessing the index of a vector. And in that function of yours you can use these checks (one time investment) and use this function for accessing later on. But again, even if you use this function, you still need to worry about what it returns in case of an out of bound index.
You can also go for some other data structure. If these items can have keys(any unique identifier), you can go for a map.
Upvotes: 1