0
votes

I have a class with vector of string (lines). I have also iterator for the current line of the vector.

I have a method that fills the lines with another container (also vector) I want to update my iterator of current line that points to the last element.

I do this and it is working fine in my compiler but in my teacher compiler it does not work.

class Document {
...
...
 std::vector<std::string> lines; 
 std::vector<std::string>::iterator currLine;
};

void Document::addLineBefore(std::vector<std::string>::iterator begin, std::vector<std::string>::iterator end)
{
  int n = std::distance(begin,end) -1;

  currLine = (lines.insert(currLine, begin, end)) + n;

}

My teacher compiler :

*Compile Error:
g++ -std=c++11 main.cpp Editor.cpp Document.cpp
Document.cpp: In member function 'void Document::addLineBefore(std::vector >::iterator, std::vector >::iterator)':
Document.cpp:31:53: error: invalid operands of types 'void' and 'int' to binary 'operator+'
currLine = (lines.insert(currLine, begin, end)) + n;
^*

What is the problem? Or maybe there is a better way to update my iterator to points the last element that added ?

1
the problem is that insert with three parameters returns void.Thomas
oops, nope. missed that.Thomas
What g++ version are you using ? On https://godbolt.org/ it compiles fine since g++4.9. Upgrade your compiler.rafix07
I think @Thomas is correct... it's possible that you and your teacher are using different compilers. Perhaps your teacher's compiler is somehow using an older, pre-C++11 version of the standard library, where the insert function returns void.NicholasM
@Thomas As I said in previous comment, OP should use 4.9 or higher, it is a bug - link bugzilla.rafix07

1 Answers

1
votes

For G++ < 4.9 it is a bug. Link on bugzilla is here.

You can ugrade your compiler or use different approach for example based on index.

void Document::addLineBefore(
    std::vector<std::string>::iterator begin, 
    std::vector<std::string>::iterator end)
{
    if (begin != end)
    {
        int idx = std::distance(lines.begin(),currLine);
        idx += std::distance(begin,end) - 1;
        lines.insert(currLine, begin, end);
        currLine = lines.begin() + idx;
    }
}
  1. Find index of currLine in vector.
  2. Add width of inserted range to idx, and substract 1 (you want to point one element before old currLine).
  3. Insert elems into vector.
  4. Calculate iterator currLine based on idx.

Live demo g++4.8