返回向量中结构体位置的索引 [英] Return index of struct position in vector

查看:33
本文介绍了返回向量中结构体位置的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎阅读了通过谷歌找到的所有主题,但没有帮助我..

I read almost every thread that I found via google, but it didn't help me out..

我在类中有一个结构:

struct animation {
    int identifier;
    int another_variable;
};

我将一堆这些结构存储在一个向量中:

I store a bunch of these structs in a vector:

static std::vector<animation> anims;

现在,我需要根据字段标识符找到结构的索引(位置).

Now, I need to find the index (the position) of a struct, based on the field identifier.

// This is what I found so far
int Animation::get_animation_index(int identifier) {        
    std::find(anims.begin(), anims.end(), identifier) - anims.begin();
 }

我们的想法是获取向量索引 anims[0] .. anims[xxx],其中存储了标识符为 xx 的结构体.

The idea is to get the vector index anims[0] .. anims[xxx] where the struct with the identifier xx is stored.

我在循环中尝试过,但后来我只能访问对象本身,而不是索引..

I tried it within a loop, but then I only get access to the object itself, not the index..

for (Animation::animation a : anims) {
    if (a.identifier == identifier) {
         // a is now the object, but I need the vector index..

有什么想法吗?

推荐答案

for (Animation::animation const& a : anims) {  // note: reference
    if (a.identifier == identifier) {
        return std::addressof(a) - std::addressof(anims[0]);
    }
}

或:

std::find_if(anims.begin(), anims.end(), 
         [ident](const animation& a) { return a.identifier == ident; })
   - anims.begin();

或者,如果动画可能不存在:

or, if the animation may not be present:

int find_index(int ident)
{
    auto it = std::find_if(anims.begin(), anims.end(), 
              [ident](const animation& a) 
              { 
                  return a.identifier == ident; 
              });
    if (it == anims.end())
        return -1; // or throw, depending on requirements
    else 
        return it - anims.begin();
}

最后,如果你的动画是按标识符排序的,你可以使用二分搜索,当向量很大时,它平均会快很多:

Finally, if your animations are sorted by identifier, you can employ a binary search, which will on average be a lot faster when the vector is large:

int find_index_sorted(const std::vector<animation>& anims, int ident)
{
    struct lower_ident
    {
        constexpr bool operator()(const animation& l, int r) const {
            return l.identifier < r;
        }

        constexpr bool operator()(int l, const animation& r) const {
            return l < r.identifier;
        }
    };
    constexpr auto pred = lower_ident();
    auto it = std::lower_bound(anims.begin(), anims.end(), ident, pred);
    if (it == anims.end() or pred(ident, *it))
        return -1;
    return it - anims.begin();
}

这篇关于返回向量中结构体位置的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆