Search code examples
c++11vectorreverse-iterator

Weird std::vector::reverse_iterator and string behavior


So I have a linear vector that I am using to store 2D value through a class: Now I want to print the values in reverse ... that is value (0,0) occupies bottom left and (max_x,max_y) occupies top right ... like a typical cartesian grid. Here is my code:

 std::string ss="";
 int i=0;
    for (std::vector<real>::reverse_iterator it= vector.rbegin(); it!=vector.rend();++it)
    {
        if (lineChanger==max_x)
        {
            std::cout<<ss<<std::endl;
            ss=""; lineChanger=0;
        }
        ss=std::to_string(*it) +"|"+ ss;
        lineChanger++;
    }

NOTE: if I do not use string and print directly , everything is fine , just the order is reversed. all my member functions work Now in my main code i use std::fill to fill the vector with the value I need (class function call). then change a few values e.g. at (0,0) and (max_x,max_y) manually. (member functions ) so say I filled with 2.38 for a 6x6 =36 sized vector then changed. Now I change the first value to be accessed ( last in the vector, first in reverse iterator) to say 3. and run the program. Output:

 2.380000|2.380000|2.380000|2.380000|2.380000|2.380000|
 2.380000|2.380000|2.380000|2.380000|2.380000|2.380000|
 2.380000|2.380000|2.380000|2.380000|2.380000|2.380000|
 2.380000|2.380000|2.380000|2.380000|2.380000|2.380000|
 2.380000|2.380000|2.380000|2.380000|2.380000|2.380000|

That is for the whole size of vector, I only get the initial std::fill value... What is wrong? i want to avoid []operator .


Solution

  • Notice your sample output contains 30 values, not 36 values. Your loop only prints the string on the iteration after it contains max_x values. So at the end of the loop, the last line of values is in the string variable but was never printed.