A
A
Artem2016-04-26 14:01:37
Programming
Artem, 2016-04-26 14:01:37

How to remove an element from a vector and then add some new ones?

There is this code:

vector<Query> queries;
...
channels.push_back(Query(i));
...
queries.erase(remove_if(queries.begin(), queries.end(), IsEnded), queries.end());

Is Ended:
bool IsEnded(const Query &aVar)
{
    bool ok = false;
    if (aVar.id==-1)
    ok = true;
    return ok;
}

The problem is that something weird happens after the deletion. When adding a new element, no errors are thrown, but when this element is passed by reference, all fields of the object are lost:
void servBegin(Query &que) {           
            cout << "    #" << que.id << endl;
        }

Outputs #0.
The transfer is carried out in a loop like this:
for(i=0;i<n;i++) {
                if(channels[i].isFree() && queries[k-1].chn_num < L) {
                    channels[i].servBegin(queries[k-1]);
                }
            }

Perhaps the cant is precisely because of the cycle?
Before removal everything works fine. How to fix?
I would be very grateful for a simple example with the removal and subsequent addition of an element to a vector.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-04-26
@ber_enot

You may have two problems.
1. The "assign" or "move" operation is written incorrectly.
2. I forgot that in std:: vector during the operation "add" or "remove" the physical movement of the object is possible and references to it are no longer valid.
Well, IsEnded is better to write like this.

bool IsEnded(const Query &aVar) { return (aVar.id == NO_ID); }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question