dimanche 5 mai 2019

How to return an iterator from a function including the end case

In c++ I need to search a vector containing a pair, in reverse, by the string. I cannot use a map because the strings are not unique and order is important. I then want to return a forward iterator if the string is found or the end iterator if the string is not found.

Please see below for my current code. I have no problem when the string is found but, if the string is not found, I get a segfault in the conditional statement in main.

vector<pair<string, int>>::iterator prev_it(const string& pred, 
        vector<pair<string, int>> prevpreds) {
    vector<pair<string, int>>::reverse_iterator rit;
    for(rit = prevpreds.rbegin(); 
            rit != prevpreds.rend(); ++rit) {
        if (rit->first == pred) {
            return (rit+1).base();}
    }
    if(rit == prevpreds.rend()) {
        return prevpreds.end();
    }
}

and in main:

int main() {
    vector<pair<string, int>> test;
    for(int i = 0; i <= 5; ++i) {
        pair<string, int> mypair;
        mypair = make_pair("X"+to_string(i%4+1), i+1);
        test.emplace_back(mypair);
    }
    string tpred = "X"+to_string(6);

    vector<pair<string, int>>::iterator tit;
    tit = prev_it(tpred, test);

    if (tit != test.end()) {
        cout << tit->first << " " << tit->second << endl;
    }
    else {cout << "This is the end." << endl;}
}

The code works if tpred is one of X1 to X4. If tpred is X6 (i.e. not an element of test) then I get a segfault. What I would like to be able to do is return the end forward iterator and then, as in main(), have a conditional based on this.

Aucun commentaire:

Enregistrer un commentaire