gpt4 book ai didi

c++ - 返回 vector 中结构位置的索引

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:30 25 4
gpt4 key购买 nike

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

我在类中有一个结构:

struct animation {
int identifier;
int another_variable;
};

我将这些结构的一堆存储在一个 vector 中:

static std::vector<animation> anims;

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

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

想法是获取 vector 索引 anims[0] .. anims[xxx],其中存储了标识符为 xx 的结构。

我在一个循环中试过了,但是我只能访问对象本身,而不是索引..

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();

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

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();
}

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

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();
}

关于c++ - 返回 vector 中结构位置的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com