简体   繁体   English

向量、迭代器和 std::find

[英]Vectors, iterators and std::find

Is there any way to use different types of iterators in different vectors?有没有办法在不同的向量中使用不同类型的迭代器? Or, is there a function that returns the position of element in vector as an integer?或者,是否有一个 function 将向量中元素的 position 作为 integer 返回?

std::vector<DWORD>::iterator it;        // Iterator

// monsterQueue is a <DWORD> vector

it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object);   
// Check do we have the object in the queue

if(it != bot.monsterQueue.end())    // If we do have it
{
    bot.monsterDists.at(it) = mobDist; // monsterDists is <int> vector
    bot.monsterCoordX.at(it) = PosX; // monsterCoordX is <int> vector
    bot.monsterCoordY.at(it) = PosY; // monsterCoordY is <int> vector too
}

That's some sample code, does anyone have any pointers?这是一些示例代码,有人有任何指示吗?

index = std::distance( monsterQueue.begin(), it );

Simply calculate简单计算

it - bot.monsterQueue.begin()

to get the index.获取索引。

Try尝试

std::vector<DWORD>::iterator it;        // Iterator

// monsterQueue is a <DWORD> vector

it = std::find(bot.monsterQueue.begin(), bot.monsterQueue.end(), object);   
// Check do we have the object in the queue

if(it != bot.monsterQueue.end())    // If we do have it
{

size_t idx = it - bot.monsterQueue.begin() size_t idx = 它 - bot.monsterQueue.begin()

    bot.monsterDists.at(idx) = mobDist; // monsterDists is <int> vector
    bot.monsterCoordX.at(idx) = PosX; // monsterCoordX is <int> vector
    bot.monsterCoordY.at(idx) = PosY; // monsterCoordY is <int> vector too
}

Also probably it will be a better idea to create a struct with 4 members 'monster',monsterDist and coordinateX and coordinateY and store the struct objects in vector.同样,创建一个具有 4 个成员 'monster'、monsterDist 和坐标 X 和坐标 Y 的结构并将结构对象存储在向量中可能是一个更好的主意。

You can use the random access in std::vectors:您可以在 std::vectors 中使用随机访问:

DWORD find_this = 0x0;
int pos = 0;
for (; i<monsterQueue.size(); ++i)
{
    if (monsterQueue[i]==find_this)
        break;
}

After the loop, pos will be where the loop broke, ie where find_this is located.在循环之后, pos 将是循环中断的位置,即find_this所在的位置。 Except, of course, if find_this is not even in the vector.当然,除非find_this不在向量中。

Have you thought about changing the underlying type of monsterQueue to an object that contains or has references/pointers to monsterDists et al您是否考虑过将 monsterQueue 的基础类型更改为包含或具有指向 monsterDists 等的引用/指针的 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM