2 Replies - 1224 Views - Last Post: 07 January 2010 - 04:02 AM Rate Topic: -----

#1 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 116
  • View blog
  • Posts: 363
  • Joined: 20-August 08

Removing Comments

Posted 06 January 2010 - 10:08 PM

I'm writing a function to remove the comments from some source code. The code is stored in a vector. Here's the relevant code that checks if a line is a comment, and if it is, it keeps erasing elements until it finds a '\n' character.

typedef std::vector<char>::iterator citer;

void Scanner::RemoveComments(std::vector<char>& textbuff) {
	for(citer x = textbuff.begin(); x != textbuff.end(); x++) {
		// check if line is comment
		if((*x) == '@') {
			for(citer y = x; (*y) != '\n'; y++) {
				textbuff.erase(y);
			}
		}
	}
} 


Everytime i call this function my program crashes. Debugging it in VS2008 Express Gives this message:

Debug Assertion Failed!

Program: ....etc

Expression:("this->_Has_container()", 0)


I'm guessing the error is obvious, but i just can't see it. Thanks in advance :D

Is This A Good Question/Topic? 0
  • +

Replies To: Removing Comments

#2 seeP+  Icon User is offline

  • D.I.C Addict

Reputation: 55
  • View blog
  • Posts: 601
  • Joined: 20-July 09

Re: Removing Comments

Posted 06 January 2010 - 11:26 PM

What line number of the code does the error point to?
Was This Post Helpful? 0
  • +
  • -

#3 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 856
  • View blog
  • Posts: 2,339
  • Joined: 20-August 07

Re: Removing Comments

Posted 07 January 2010 - 04:02 AM

Two problems: firstly, your loop might overrun if the comment is not terminated with a '\n' (perhaps its the final 'line' in your vector)
Secondly, erasing an element will invalidate all iterators associated with that container.

Instead of erasing elements 1-by-1 (which is inefficient anyway), you should erase a range of elements. e.g.
    citer y = std::find(x, textbuff.end(), '\n');
    if( y != textbuff.end() )
        x = textbuff.erase(x,y); 
x becomes valid again - the result of erase will be an iterator to the next element (either your '\n' or textbuff.end())

This post has been edited by Bench: 07 January 2010 - 04:11 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1