Search code examples
c++queuestd-pair

Queue returns wrong value of pair.first


I have weird problem: after popping (previously pushed pair of ints) from queue I get proper value of second element of pair and completely random value of first element.

For example if I push pair<int, int> = (368, 125) then I get pair = (14416384, 125).

I cannot use own struct {int first, int second} instead of pair because later I need to store these pair of ints into set to be able to find them quickly and I don't want to change the app significantly.

Do you have any idea how to fix it?

The fragment of code is shown below:

vector<pair<int, int>> objekt;
set<pair<int, int>> przetworzone;
int pointX = m_imgIN.pointX;
int pointY = m_imgIN.pointY;
BYTE currPixel = m_imgIN.m_bitmapObject.GetPixel8(pointX, pointY);

if (currPixel > 0)
{
    queue<pair<int, int>> kolejka;
    kolejka.push(make_pair(pointX, pointY));  //<- here: pointX=368 and pointY=125 

    while (kolejka.size() != 0)
    {            
        pair<int, int> p;
        p = kolejka.front(); //<- here: p.first=14416384 and p.second=125
        kolejka.pop();

        if (m_imgIN.m_bitmapObject.GetPixel8(p.first, p.second) > 0)
        {
            //...

Solution

  • So your code works fine: http://ideone.com/ainPyU The exact values that you input are read back.

    kolejka is locally created and in the code you have shown only ever has 1 element added to it, then you loop over it's contents. That doesn't make sense unless there's code that you haven't shown us. I suspect that unshown code is what's actually causing the problem.

    So working under that premise that something else happens between these lines, I'll suggest that you are writing out of bounds to another container and stomping on the contents of your first element. I'd debug this by setting a memory breakpoint on the address of the 1st element in kolejka's first member.