checking if pointer points within an array

后端 未结 6 2036
半阙折子戏
半阙折子戏 2020-12-06 01:25

Can I check whether or not a given pointer points to an object within an array, specified by its bounds?

template 
bool points_within_array         


        
6条回答
  •  一个人的身影
    2020-12-06 02:01

    Could you not do this with std::distance, i.e. your problem effectively boils down to:

    return distance(begin, p) >= 0 && distance(begin, p) < distance(begin, end);
    

    Given this random access iterator (pointer) is being passed in, it should boil down to some pointer arithmetic rather than pointer comparisons? (I'm assuming end really is end and not the last item in the array, if the last then change the less than to <=).

    I could be way off the mark...

提交回复
热议问题