0

I'm making a bottom-top rgb pixel array to top-bottom. I've checked the value of something and it gives me the expected output. No value is greater than obj.size() and no value is less than 0, I don't know what's up :/

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    if (y_height <= 1) { return obj; } // nothing to reverse if its only one row 

    std::vector<std::string> new_v;

    for (int h = 0; h < y_height; h++)
    {
        for (int i = x_width; i >= 1; i--)
        {
            int something = (obj.size() - i) - (x_width*h); // error
            std::string val = obj[something];

            new_v.push_back(val);
        }
    }

    return new_v;
}
Deidrei
  • 2,125
  • 1
  • 14
  • 14

2 Answers2

1

You should be able to replace your entire function with:

#include <algorithm>

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    std::reverse(obj.begin(), obj.end());
    return obj;
}

Note that this will put the lower-left corner in the upper-right corner. This line in your code suggests you only want to mirror top-to-bottom:

if (y_height <= 1) { return obj; } // nothing to reverse if its only one row 

If you want to swap rows, but keep the pixels left-to-right within each row, then the following ought to do:

#include <algorithm>

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    int top_row = 0, bot_row = y_height - 1;

    while (top_row < bot_row)
    {
        std::swap_ranges( obj.begin() + top_row * x_width,
                          obj.begin() + top_row * (x_width + 1),
                          obj.begin() + bot_row * x_width );

        top_row++;
        bot_row--;
    }

    return obj;
}
Joe Z
  • 17,413
  • 3
  • 28
  • 39
0

If you are required to write your own version of reverse:

std::vector<std::string> BMP_READER::TopBottom(std::vector<std::string> obj)
{
    for (std::size_t i = 0; i < obj.size() / 2; ++i)
    {
        std::swap(obj[i], obj[obj.size() - i - 1]);
    }
    return obj;
}

Which is a single for-loop that only iterates through half of the elements.

Otherwise, use std::reverse.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42