简体   繁体   中英

Find a position and return an iterator doesn't work

template<typename T>
void findposition(T t, long value, typename T::iterator &before, typename T::iterator &position) {
        typename T::iterator it = t.begin();
        while(it != t.end()) {
            before = it;
            position = it;
            if(*it > value) {
                if(before != t.begin()) {
                    before = --it;
                }
                break;
            }
            ++it;
        }
    }

vector<long>::iterator itVectorBefore;
vector<long>::iterator itVectorPosition;
findposition(myVector, 31, itVectorBefore, itVectorPosition);
myVector.insert(itVectorPosition, 31);

I don't understand why this piece of code is no working. When i ran it, i will get a segmentation fault. Another strange thing is, when du call findposition(myVector, 1, itVectorBefore, itVectorPosition). Both Iterators will hold a value of 0. I used gdb to investigate, but i couldn't find what is going wrong, because the before has the right value in the function findposition.

When someone of you has an idea what i have made wrong. I would be very pleased for an explanation.

Thanks for you help.

  1. Neither before nor after get initialized when the container is empty.

     typename T::iterator it = t.begin(); while(it != t.end()) { // When the input is empty, nothing // is set to before or after. 
  2. The returned iterators are on a copy of the input argument.

    You should change:

     template<typename T> void findposition(T t, long value, typename T::iterator &before, typename T::iterator &position) { 

to

    template<typename T>
    void findposition(T& t, long value,
                      typename T::iterator &before,
                      typename T::iterator &position) {

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