C++ Vector subscript out of range (but it's not)

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;
}

Answers


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;
}

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.


Need Your Help

Get Active Directory URL inside WebPart in Sharepoint

c# sharepoint active-directory

is there a way to find out the current Active Directory's URL inside SharePoint webpart?

Submitting form via multiple partials

ruby-on-rails-3 jquery

I have a really long form which I would like to break up into about 5 partials. When the user hits 'Next' at the bottom of each partial I want to use AJAX to load the next partial until the last p...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.