简体   繁体   中英

How to convert auto (for vector<string>) from c++11 to c++98?

I have this code in C++11:

vector<int> stariFinale;

bool LexAnalyzer::eStareFinala(int q)
{
    for (auto x : stariFinale)
        if (q == x)
            return true;
    return false;
}

And I tried to convert it to C++98 like:


bool Analizator_L::eStareFinala(int q)
{
    for (vector<int>::iterator x = stariFinale.begin(); x!= stariFinale.end(); x++)
        if (q == x)
            return true;
    return false;
}

which gives me the error no match for 'operator==' in 'q==x'

Please, help.

Now you've got an iterator, not the value, so you must dereference it. And please use prefix ++, not postfix ++. Postfix ++ needs to create a temporary, prefix ++ not, compare the enforcement section of http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rp-waste .

for (vector<int>::iterator x = stariFinale.begin(); x != stariFinale.end(); ++x)
    if (q == *x)
        return true;

Another option which requires less code changes is to have the iterator and the old x variable:

for (vector<int>::iterator iter = stariFinale.begin(); iter != stariFinale.end(); ++iter) {
    int x = *iter;
    if (q == x)
        return true;
}

Even better in your case: don't write the loop yourself, use a standard algorithm (compare http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-lib ). Your function could be implemented by using std::find .

return std::find(stariFinale.begin(), stariFinale.end(), q) != stariFinale.end();

Like this if (q == *x)

Use * to get the element that the iterator is pointing at.

This code will work in C++98 and C++11 or later:

bool LexAnalyzer::eStareFinala(int q)
{
    return std::find( stariFinale.begin(), stariFinale.end(), q ) != stariFinale.end();
}

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