C++ List Insert Iterator - c++

A family object contains a linked list of Person objects, and as such, a function exists within the Family class to insert Person objects into a ListedList called people.
I’m having some trouble where only certain Person objects are being added to the people linked list. I have omitted a number of other functions, as I was (hopefully) able to determine the problem is occurring within the insertPerson() function in the Family class.
The for loop within insertPacket() is looping through each ‘Person’ object as intended (refer to commented ‘cout’). However, things break down in the if statement..
if (person_id < itr->get_person_id())
{
Person *psn = new Person(person_id, name);
people.insert(itr, *psn);
break;
}
If a person_id is less than the get_person_id() in the linked list, it executes and inserts it at the beginning of the list, however if it is not, it just skips it entirely...

You're fundamental bug is here, in insertPerson:
for(itr = people.begin(); itr != people.end(); itr++)
{
if (id < itr->get_person_id())
{
people.insert(itr, Person(id, text));
break;
}
}
What if the person's id is greater than all of the current list members? Then the insert will never happen as you will reach end() and break the loop. This should be used to find the insertion point, which can include end().
You can find the proper insertion point doing this:
for(itr = people.begin(); itr != people.end(); itr++)
{
if (itr->get_person_id() < id)
break;
}
people.insert(itr, Person(id, text));
Note that this will allow duplicate insertions for a given id. Not sure if you care about that. Finally, the same problem exists for insertion of a Family, so you probably want to fix that after this.
Best of luck.

Try
if (input_id < itr->get_familyid())
{
Family *fam = new Family(input_id);
families.insert(itr, *fam);
break;
}
std::list insert according to this link is
iterator insert (iterator position, const value_type& val);

Related

c++ Iterating over a list of objects and deleting a object

I have a list of objects and I want to delete a certain object once it hits the if condition. But I am having issues with it working. Mostly because the if condition is throwing the error.
Also I don't know if I need to create a temp folder value and let that be my if condition? I'm honestly kind of confused on iterators and any extra information might be helpful.
void removeFolder(string fName)
{
list<Folder> folders = this->getFolders();
for (list<Folder> itr = folders.begin(); itr != folders.end();)
{
if (fName == *itr)
itr = folders.erase(itr);
else
++itr;
}
}
I think you have correct idea, but you are doing wrong thing. folders is:
list<Folder> folders
Than you are iterating different elements "folder" not "Folder":
for (list<folder> itr = folders.begin(); itr != folders.end();)
I think this should be rather:
for (list<Folder>::iterator itr = folders.begin(); itr != folders.end();)
Now once you are iterating correct objects make comparisons that make sense, not string to object:
if (fName == *itr)
but rather compare string to string, I assume your Folder class has some method to get folder name i.e:
if (fName == (*itr).getFolderName())
I'm sure there is this question answered somewhere already, but the code is simple:
You only need to use std::list<Folder>::remove_if().
void removeFolder(const std::string& fName)
{
std::list<Folder>& folders = getFolders();
folders.remove_if([&fName](Folder& item){return item.name == fName;});
}
As others have noted, there are other problems with your code that I've tried to fix. In particular, you are probably comparing some sort of name member with the fName variable. Also there is no need to pass the fName string by value into the removeFolder function, and presumably you need to modify not a local copy of folders, but some list existing outside of the function.

Inserting values from Vector to Map

i got some issues trying to put the values of my vector in a new map (maMap)
If someone could explain me what contain my ItemIterator or how to do...
map<std::string,Employee*> Entreprise::convertiVectorMap() const
{
map<std::string,Employee*> maMap;
vector<Employee*>::const_iterator ItemIterator;
for(ItemIterator = vector_employe.begin(); ItemIterator != vector_employe.end(); ItemIterator++)
{
maMap.insert(std::pair<string,Employee*>(ItemIterator->getNom(),ItemIterator));
}
}
Your map is of <std::string, Employee*>, but you are trying to add an iterator as the second element of the pair. You need to dereference the iterator to get the Employee pointer.
maMap.insert(std::pair<string,Employee*>((*ItemIterator)->getNom(), *ItemIterator));
Or to save from dereferencing the same iterator twice, you could just use a range based for loop. As #CaptainObvlious mentions, you can also use std::make_pair to add to your map.
for(auto const employee: vector_employe)
{
maMap.insert(std::make_pair(employee->getNom(), employee));
}
You forgot to derefrence your iterator:
maMap.insert(std::pair<string,Employee*>((*ItemIterator)->getNom(),*ItemIterator));
And since everyone asks for a revamped version of your code here we go:
map<std::string,Employee*> Entreprise::convertiVectorMap() const
{
map<std::string,Employee*> maMap;
for(vector<Employee*>::const_iterator ItemIterator = vector_employe.cbegin(),
ItemIteratorEnd = vector_employe.cend();
ItmeIterator != ItemIteratorEnd; ++ItemIterator)
{
Employee* ptr = *ItemIterator;
maMap.insert(std::make_pair(ptr->getNom(),ptr));
}
}
You can also use ranged based for if you're at least in C++11.

Pointer not derefencable from a list

I have the two classes Player and Team, where each player class has a pointer to the team
class Player{
private: Team* team;}
and each team has a list of pointers to the players
class Team{
private: list<Player*> playerlist;}
Now i want to find out in which team a player plays by adressing him in the list. Afterwards i want to be able to adress the team for something like team.getid()
I tried the following solution for a function:
std::list<Team>::iterator* teamsearch(std::list<Team> a, int b)
{
int i = 0;
std::list<Team>::iterator Listitem;
std::list<Team>::iterator* Listitemtest = &Listitem;
while (i == 0){
for (Listitem = a.begin(); Listitem != a.end(); ++Listitem)
{
if (Listitem->getteamID_() == b)
i++;
Listitemtest = &Listitem;
}
};
std::cout << "TeamID: " << (*Listitemtest)->getteamID_() << std::endl;
return Listitemtest;
}
The idea is that it returns an iterator which points to the adress of the team of the player. Is this correct ?
Then i tried to adress the teams by dereferencing the iterator again by this way:
Team team;
team.setteamID_(0);
team.setteamname_("team1");
Teamvector.push_back(team);
std::list<Team>::iterator Listitem;
Listitem = *teamsearch(Teamvector, 0);
which gives me a runtime error in MSVC120.dll ...include\list: list iterator not derefencable
Somehow it seems like the iterator points to the end of the teamlist ?
You are returning a pointer to a local variable. The iterator which is pointed to by the returned pointer, is already destroyed when the function returns.
You should just return by value, don't bother with pointers here. An iterator is trivial to copy.
Nobody mentioned this yet but the first major problem is that this line:
Listitemtest = &Listitem;
means that Listitemtest points to the iterator Listitem itself. It does not point to the thing that ListItem is pointing at.
Therefore when you go (*Listitemtest)->getteamID_(), this is equivalent to Listitem->getteamID_(). But since Listitem is now at a.end() this is an invalid dereference.
To fix this, you should stop using pointers to iterators. I can't think of a single situation ever where it is a good idea to use pointers to iterators - instead it's a sign that you're doing something wrong.
Instead, make Listitemtest be an iterator of the same type as Listitem, and then just set it by going Listitemtest = Listitem. Then it will point that the item you are interested in.
However, having fixed this, you still can't return Listitemtest yet. That is because it points into std::list<Team> a, which is a local variable to your function and will stop existing when you return. To fix this, make the parameter be std::list<Team> &a. Then you can safely return the iterator.

c++ process scheduling questions

I am working on code which implements a Multilevel Feedback Queue Scheduler. There is something not clear in a part of the code:
void Scheduler_MFQS :: fill_queue(int clk) {
list<Process>::iterator itr;
for(itr = processes.begin(); itr != processes.end(); itr++) {
if((itr -> has_arrived(clk)) && (!queues[0].contains(*itr))) {
Process tmp (*itr);
queues[0].add_process(tmp);
remove(processes.begin(), processes.end(), *itr);
}
}
}
What this basically does is just put the process into the base queues under some condition. But i don't know what Process tmp (*itr); means? However, it compiles legally. Does that mean create a Process object called tmp? But what is the next, iterator (*itr) mean in c++?
"Process tmp (*itr);" mean?
It calls Process(const Process& &) copy constructor to create tmp object;
what is the next, iterator (*itr) mean in c++?
itr is std::list::iterator type, it's a pointer to current list node. *itr is getting the content of itr, which is a Process.
Your code can enhance a bit, demo as below:
// list<Process>::iterator itr; // move this into for loop, narrow variable scope and lifetime
/*auto if C++11*/
processes.unique(); // you actually only want unique processes from list
for(list<Process>::iterator itr = processes.begin(); itr != processes.end(); ++itr)
^^ call preincrement, faster
{
if((itr -> has_arrived(clk)) /*&& (!queues[0].contains(*itr))*/) {
^^ process list contains unique item only, no need to compare
//Process tmp (*itr); comment out this line, save one object copy
queues[0].add_process(*itr);
//remove(processes.begin(), processes.end(), *itr);
// You don't need to clear item in the loop
}
}
processes.clear(); // or swap with an empty list
// std::list<Process> p2;
// p2.swap(ps);
itr is the iterator which points to some container element(list in your case). When you use asterisk(*) on iterator you gain access to its content i.e. to the actual element of the list. In your case it is a Process object.

C++ map iteration with deletion

I couldn't find an instance of how to do this, so I was hoping someone could help me out. I have a map defined in a class as follows:
std::map<std::string, TranslationFinished> translationEvents;
TranslationFinished is a boost::function. I have a method as part of my class that iterates through this map, calling each of the functions like so:
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(); it != translationEvents.end(); ++it)
{
it->second(this);
}
}
However it's possible for a function called by it->second(this); to remove an element from the translationEvents map (usually itself) using the following function:
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool removed = false;
auto it = translationEvents.find(index);
if (it != translationEvents.end())
{
translationEvents.erase(it);
removed = true;
}
return removed;
}
doing this causes a debug assertion fail when the DispatchTranslationEvents() tries to increment the iterator. Is there a way to iterate through a map safely with the possibility that a function call during the iteration may remove an element from the map?
Thanks in advance
EDIT: Accidently C/Pd the wrong Remove Event code. Fixed now.
map::erase invalidates the iterator being deleted (obviously), but not the rest of the map.
This means that:
if you delete any element other than the current one, you're safe, and
if you delete the current element, you must first get the next iterator, so you can continue iterating from that (that's why the erase function for most containers return the next iterator). std::map's doesn't, so you have to do this manually)
Assuming you only ever delete the current element, then you could simply rewrite the loop like this:
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
auto next = it;
++next; // get the next element
it->second(this); // process (and maybe delete) the current element
it = next; // skip to the next element
}
Otherwise (if the function may delete any element) it may get a bit more complicated.
Generally speaking it is frowned upon to modify the collection during iteration. Many collections invalidate the iterator when the collection is modified, including many of the containers in C# (I know you're in C++). You can create a vector of events you want removed during the iteration and then remove them afterwards.
After reading all other answers, I am at an advantage here... But here it goes.
However it's possible for a function called by it->second(this); to remove an element from the translationEvents map (usually itself)
If this is true, that is, a callback can remove any element from the container, you cannot possibly resolve this issue from the loop itself.
Deleting the current callback
In the simpler case where the callback can only remove itself, you can use different approaches:
// [1] Let the callback actually remove itself
for ( iterator it = next = m.begin(); it != m.end(); it = next ) {
++next;
it->second(this);
}
// [2] Have the callback tell us whether we should remove it
for ( iterator it = m.begin(); it != m.end(); ) {
if ( !it->second(this) ) { // false means "remove me"
m.erase( it++ );
} else {
++it;
}
}
Among these two options, I would clearly prefer [2], as you are decoupling the callback from the implementation of the handler. That is, the callback in [2] knows nothing at all about the container in which it is held. [1] has a higher coupling (the callback knows about the container) and is harder to reason about as the container is changed from multiple places in code. Some time later you might even look back at the code, think that it is a weird loop (not remembering that the callback removes itself) and refactor it into something more sensible as for ( auto it = m.begin(), end = m.end(); it != end; ++it ) it->second(this);
Deleting other callbacks
For the more complex problem of can remove any other callback, it all depends on the compromises that you can make. In the simple case, where it only removes other callbacks after the complete iteration, you can provide a separate member function that will keep the elements to remove, and then remove them all at once after the loop completes:
void removeElement( std::string const & name ) {
to_remove.push_back(name);
}
...
for ( iterator it = m.begin(); it != m.end(); ++it ) {
it->second( this ); // callback will possibly add the element to remove
}
// actually remove
for ( auto it = to_remove.begin(); it != to_begin.end(); ++it ) {
m.erase( *it );
}
If removal of the elements need to be immediate (i.e. they should not be called even in this iteration if they have not yet been called), then you can modify that approach by checking whether it was marked for deletion before executing the call. The mark can be done in two ways, the generic of which would be changing the value type in the container to be a pair<bool,T>, where the bool indicates whether it is alive or not. If, as in this case, the contained object can be changed you could just do that:
void removeElement( std::string const & name ) {
auto it = m.find( name ); // add error checking...
it->second = TranslationFinished(); // empty functor
}
...
for ( auto it = m.begin(); it != m.end(); ++it ) {
if ( !it->second.empty() )
it->second(this);
}
for ( auto it = m.begin(); it != m.end(); ) { // [3]
if ( it->second.empty() )
m.erase( it++ );
else
++it;
}
Note that since a callback can remove any element in the container, you cannot erase as you go, as the current callback could remove an already visited iterator. Then again, you might not care about leaving the empty functors for a while, so it might be ok just to ignore it and perform the erase as you go. Elements already visited that are marked for removal will be cleared in the next pass.
My solution is to first create a temporary container, and swap it with the original one. Then you can iterator through the temporary container and insert the ones you want to keep to the original container.
void BaseSprite::DispatchTranslationEvents()
{
typedef std::map<std::string, TranslationFinished> container_t;
container_t tempEvents;
tempEvents.swap(translationEvents);
for(auto it = tempEvents.begin(); it != tempEvents.end(); ++it)
{
if (true == it->second(this))
translationEvents.insert(it);
}
}
And the TranslationFinished functions should return true if it want to be keeped and return false to get removed.
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool keep = false;
return keep;
}
There should be a way for you to erase a element during your iteration, maybe a little tricky.
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
//remove the "erase" logic from second call
it->second(this);
//do erase and increase the iterator here, NOTE: ++ action is very important
translationEvents.erase(it++);
}
The iterator will be invalid once the element is removed, so you can not use that iterator to do increase action anymore after you remove it. However, remove an element will not affect other element in map implementation, IIRC. So suffix ++ will copy the iter first and increase the iterator right after that, then return the copy value, which means iterator is increased before erase action, this should be safe for you requirement.
You could defer the removal until the dispatch loop:
typedef boost::function< some stuff > TranslationFunc;
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool removed = false;
auto it = translationEvents.find(index);
if (it != translationEvents.end())
{
it->second = TranslationFunc(); // a null function indicates invalid event for later
removed = true;
}
return removed;
}
protect against invoking an invalid event in the loop itself, and cleanup any "removed" events:
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
// here we invoke the event if it exists
if(!it->second.empty())
{
it->second(this);
}
// if the event reset itself in the map, then we can cleanup
if(it->second.empty())
{
translationEvents.erase(it++); // post increment saves hassles
}
else
{
++it;
}
}
}
one obvious caveat is if an event is iterated over, and then later on deleted, it will not get a chance to be iterated over again to be deleted during the current dispatch loop.
this means the actual deletion of that event will be deferred until the next time the dispatch loop is run.
The problem is ++it follows the possible erasure. Would this work for you?
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(), next = it;
it != translationEvents.end(); it = next)
{
next=it;
++next;
it->second(this);
}
}