开发者

Shows an assertion error at runtime in vector c++

I want to erase an element from a vector in c++, but it shows a runtime assertion error.

My code is:

   int i=0;
        for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){
            SOCKET clientSocket=*socketIterator;

            isTrue=getBufferData(strt,stp,rm,clientSocket);
            if(!isTrue){
                vectClientSocket.erase(vectClientSocket.begin()+i);

                vector<RMLObserver*>::iterator it;
                for(it=vectRMLObserver.begin();it<vectRMLObserver.end();it++)
                {
                    RMLObserver *observer = (RMLObserver*)*it;
                    observer->in开发者_运维百科fosetSent(info->getRMLThinTranskportToken());
                }
            }
            else
                ++socketIterator;

            i++;
        }

When one element is removed it shows a runtime error,

Shows an assertion error at runtime in vector c++

Please help me...thank you in advance.


You need to update your iterator after erasing an element:

socketIterator = vectClientSocket.erase(socketIterator);

see also std::vector<..>::erase(..) documentation

[EDIT]

Use the operator !=(..) to compare the iterators:

for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){


After this line:

 vectClientSocket.erase(socketIterator);

socketIterator is an invalid iterator because where it used to point has been erase. Between this line and the next iteration through your loop you never give it a valid value so this line in the next iteration is an invalid dereference.

SOCKET clientSocket=*socketIterator;

As Simon points out, even before this, the loop condition socketIterator<vectClientSocket.end() will also cause undefined behavior as socketIterator is no longer a valid iterator into vectClientSocket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜