0

I'm just iterating/subscripting for values inside a container or string to see if those values are what I want. I just want to know which way (between numbers1 and numbers2) is more efficient.

bool isnumber (const char character)
{
    return(character>=48 && character<=57);             
}

template <typename T> bool numbers1(const T &str)
{
    if(!str.empty())
    {
        for (auto it=str.cbegin(); it!=str.cend(); ++it) if (!isnumber(*it)) return false;

        return true;
    }
    else return false;
}

template <typename T> bool numbers2(const T &str)
{
    if(!str.empty())
    {
        for (auto &i : str) if(!isnumber(i)) return false;

        return true;
    }
    else return false;
}
Yaz
  • 93
  • 1
  • 8

1 Answers1

0

Range-based for loops in C++ are essentially just shorthand for a loop that uses begin() and end() generally with iterators. In numbers2, the compiler expands the loop to use str.begin and str.end. The only real difference on a compiled level is that your handwritten iterator loop uses cbegin() and cend() instead of begin() and end().

Just further reading: If you make a class that implements begin() and end() then you will be able to perform range-based for loops on that class: How to make my custom type to work with "range-based for loops"?

Community
  • 1
  • 1
Baladash
  • 1
  • 1
  • "The only real difference on a compiled level is that your handwritten iterator loop uses cbegin() and cend() instead of begin() and end()" - and the fact that range-for only checks the end condition once whereas a classic for loop tests it on each iteration. – Jesper Juhl Nov 29 '16 at 14:57
  • So that means that range-for loops should not alter the container due to the fact than end() can be invalidated because of it? – Yaz Nov 29 '16 at 19:33