c++ 如何从std::vector中的一个元素的引用中获取它的索引?

zi8p0yeb  于 10个月前  发布在  其他
关注(0)|答案(1)|浏览(138)

如何优雅地(以现代C++的方式)编写一个函数,返回一个向量元素的索引,将这个向量作为参数,并引用它的一个元素?
我们将不胜感激。

#include <vector>

template <class T>
std::size_t GetIndexFromRef(std::vector<T> &vec, T &item)
{
...
};

字符串

qni6mghb

qni6mghb1#

这就是诀窍:

template <class T>
std::size_t GetIndexFromRef(std::vector<T> const &vec, T const &item)
{
    T const *data = vec.data();

    if(std::less<T const *>{}(&item, data) || std::greater_equal<T const *>{}(&item, data + vec.size()))
        throw std::out_of_range{"The given object is not part of the vector."};
    
    return static_cast<std::size_t>(&item - vec.data());
};

字符串
我使用std::lessstd::greater_equal,因为([comparisons.general§2]):
对于模板lessgreaterless_­equalgreater_­equal,任何指针类型的专门化都会产生与实现定义的指针上的严格全序一致的结果([defns.order.ptr])。
[* 注1*:如果a < b对于类型为P的指针ab定义良好,则(a < b) == less<P>()(a, b)(a > b) == greater<P>()(a, b),依此类推。
否则,与不属于向量的对象执行比较将是UB。

相关问题