简体   繁体   中英

runtime assertion error while operating on vector c++

i have an array arr of vectors and I want to search and remove from the array vectors which have a specific value in one of elements, call it elementA . It happens to me, that if you have a look inside the array, such condition is fullfilled for a couple of consecutive vectors in a row.

In your code:

int eStart = -1; int eEnd = -1; 
for ( int i=0; i<arr.size()-1; i++ )
{
    if ( -1 == eStart && arr[i].getElementA() == 0 )
        eStart = i;
    if ( arr[i].getElementA() == 0 )
        eEnd = i;
}
arr.erase( arr.begin()+eStart, arr.begin()+eEnd ); 

The second iterator passed to erase have to be One past the last you want to erase (and call erase only if you finded some element that need to be erase):

arr.erase( arr.begin()+eStart, arr.begin()+eEnd +1 ); 

The error: checking the "range of iterators" during arithmetic's: the result have to be >= the first element, and <= the last element. begin()-1 don't fit: that is what you have when you don't check if finded, that is when eRtart=-1 .

_SCL_SECURE_VALIDATE_RANGE(
        _Myptr + _Off <= ((_Myvec *)(this->_Getmycont()))->_Mylast &&
        _Myptr + _Off >= ((_Myvec *)(this->_Getmycont()))->_Myfirst);
    _Myptr += _Off;

NOTE: It is not recomended to inherit from std::containers.

int eStart = -1; int eEnd = -1; 
for ( int i=0; i<arr.size()-1; i++ )
{
    if ( -1 == eStart && arr[i].getElementA() == 0 )
        eStart = i;
    if ( arr[i].getElementA() == 0 )
        eEnd = i;
}
if(estart != -1)    // added check <---------------------------------
    arr.erase( arr.begin()+eStart, arr.begin()+eEnd ); 

You could use remove-erase idioms to simplify your code:

struct IsZeroA
{
  IsZeroA() {}
  bool operator()(ClassA a) 
  {
    return a.getElementA() == 0;
  }
};

arr.erase(std::remove_if(arr.begin(), arr.end(), IsZeroA()), arr.end());

OR use lambda if you use C++11

arr.erase(std::remove(arr.begin(), arr.end(), 
         [](const ClassA& a){ return a.getElementA() == 0; }));

Now we don't need to review your code, but provide a „general“ solution.

I understand you explicitly want to take advantage of the fact that the elements to erase are consecutive.

We will use the predicate IsZeroA introduced by @billz .

auto first=find_if(arr.begin(), arr.end(), IsZero()  );
if(first!=arr.end())
{
    auto last= find_if_not(first, arr.end(), IsZero()  );
    arr.erase(first,last);
}

It can be reduced to:

auto  first = find_if  (arr.begin(), arr.end(), IsZero()  );
arr.erase( first, find_if_not(first, arr.end(), IsZero()) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM