views:

514

answers:

6

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?

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?

A: 

You can use the random access in 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, i.e. where find_this is located. Except, of course, if find_this is not even in the vector.

mizipzor
+5  A: 

Simply calculate

it - bot.monsterQueue.begin()

to get the index.

Frederik Slijkerman
+1. Can I suggest you also mention that this works because a vector is a RandomAccessContainer?
j_random_hacker
+11  A: 
index = std::distance( monsterQueue.begin(), it );
Timbo
better to use the difference_type than int for the distance
Edouard A.
You are right, I edited and removed the type declaration.
Timbo
A: 

Have you thought about changing the underlying type of monsterQueue to an object that contains or has references/pointers to monsterDists et al

Patrick
+3  A: 

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

    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.

Nitin Bhide
A: 

Thanks a lot everyone, you've really helped me. I'll be changing the type of the vectors to one vector which is holding all data, it'll make everything easier.

Ahmed