This may be a simple answer, but after self teaching myself on vectors for a few hours of I haven't been able to find the answer. I'm using class objects in a vector, and trying to complete the delete functionality according to a class variable.

#Identify BUFFER 8
class CObject;

char* str;
char identifier[BUFFER] = "";
int j;

vector<CObject> group(0);
vector<CObject>::iterator itr = group.begin();

//code goes through some menu options.  Some elements will be added to the vector

/***Erase functionality**/
str = getInput(); //function gets user input, returns char *
strcpy_s(identifier, BUFFER, str);

for(j = 0; j < group.size(); j++) //browses through the vector
	if (strcmp(identifier, group[j].getID()) == 0)
		break;  //match was made, 

if (j == fleet.size())
	cout << "ID \"" << identifier << "\" not found." << endl;
	*itr =; //***ERROR***

This compiles, but when I run the program it crashes on the line specified, from the debugger it looks like itr doesn't initialize at all. The logic works, as I use the same loops to select specific vector items for display. But to erase an item in the vector I need an iterator, and that's what I'm having trouble getting. At first I thought it could be something with my class, but testing it out with a vector<int> I get the same problem. So how do I accomplish this? Am I missing something simple?

line 10: That won't work because the vector is an empty vector. Wait until you get ready to use the iterator before assigning it to begin().

you could code that j loop using an iterator instead of an int counter

vector<CObject>::iterator it;
for(it = group.begin(); it != group.end(); it++)
      if (strcmp(identifier, it->getID()) == 0) 

If you make getID() return std::string instead of char* you don't need to call strcmp().

Yes that was it, thanks. That iterator loop is much cleaner as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.