I wrote a function that is supposed to crop a 2d vector starting at point r, c. The rectangle from there should have rows rows and cols columns.

void pgm_crop( vector <IVec> p, int r, int c, int rows, int cols )
{
    int count = 0;      //first count variable
    int count2 = 0;    // 2nd count variable

    for( count = 0; count < r; count++ )
    {
        if( count + 1 != r )
        {
            p.erase( p.begin() + count );   // erase rows before given point
        }
        else
            p.resize( rows );   // resize to number of rows
            for( count2 = 0; count2 < c; count2++ )
            {
                if( count2 + 1 != c )
                {
                    p[count].erase( p[count].begin() + count2 ); // erase elements before given point
                }
                else
                    p[count].resize( cols );    // resize to number of columns
            }

    }
}

The output i get is weird. It duplicates rows instead of deleting them

It's not obvious to me what you intend for this code to do. On lines 10 and 18, your comment suggests you intend to remove multiple elements on these lines. However, I see ONE argument given to the erase function. According the the spec, supplying ONE argument will remove ONE element. To erase more than one element, you need TWO arguments.

http://www.cplusplus.com/reference/vector/vector/erase

In addition, your indentation suggests that line 14 is intended to be part of line 12's "else" block. However, no bracket follows line 12, so line 13 and only line 13 makes up line 12's "else" block. If you intend for that not to be the case, you need to add some brackets. If the code is in fact correct, to make your intent clear, you should un-indent lines 14 to 22.

It's not clear what you are trying to do with this code and I am not familiar with the pgm format, so I can't really suggest how to fix it. But your description suggests that you perhaps want to call the erase function with TWO arguments, not one, in order to remove a RANGE of elements. As for why rows are being duplicated, perhaps you are resizing the vector LARGER rather than smaller? Hard to say since I don't know what assumptions to make regarding initial vector size and the function arguments, but the description below sounds like that may be the case.

http://www.cplusplus.com/reference/vector/vector/resize/

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.