简体   繁体   中英

c++ stl vector iterator insert segmentation fault

          std::vector<struct::event>::iterator it;
          std::vector<struct::event>::iterator last=myvector.end();

          for (it=myvector.begin(); it<=last; it++){

            if(mysignal.declination<(*last).declination){

              if (mysignal.declination>=(*it).declination && mysignal.declination<(*(it+1)).declination){
                myvector.insert(it+1, mysignal);
                break;
              }
            }
            if (mysignal.declination>=(*last).declination){
              myvector.push_back(mysignal);
              break;
            }


            }

I have a vector called myvector with events that are sorted with the declination. now I want to add mysignal to this vector on the right place. but i always get a seg fault after a few events which refers to: if(mysignal.declination<(*last).declination). I just can't see what is wrong.

Your loop is wrong, read the docs :

Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.

You can't dereference end() , it provides a way of knowing that you have overrun the container, so your loop condition should be it != myvector.end() , and last is wrong as well.

end() does not refer to the last element in the container, you need to change your condition as follows.

for (it=myvector.begin(); it != last; it++){

You have other broken logic as well that is dereferencing last that you need to fix.

As others have said, C++ iterators define a half-open interval ( '[begin()...end())' ), which is what you should probably be using in most other cases as well. And although it works with iterators from a vector, in general, iterators do not support <= (nor < ); the standard idiom for a loop is:

for ( auto current = container.begin();
        current != container.end();
        ++ current ) ...

(In the most likely case that you cannot count on C++11, you'll have to write out the full iterator type, rather than use auto . Although auto is one of the few things from C++11 that seems to work with VC++11 and with recent versions of g++, so if those are the only targets you're concerned with, and you can be sure of always having very recent versions, you can use it.)

Also, if you want to access the last element of the vector in the loop, myvector.back() will return a reference to it. ( myvector.back() is undefined behavior if the vector is empty, but if the vector is empty, you won't enter the loop.)

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