c++performancec++11

std::find_if vs manual loop, which one is better?


void func1(const std::map<int, int>& mp) {
    auto it = std::find_if(mp.begin(), mp.end(), [](const auto& it){
        return (it.second == 2);
    });
    std::cout << (it->first);
}

void func2(const std::map<int, int>& mp) {
    for (auto it = mp.begin(); it != mp.end(); ++it) {
        if (it->second == 2) {
            std::cout << (it->first);
            break;
        }
    }
}

int main() {
    std::map<int, int> mp {{1, 2}, {3, 4}};
    func1(mp);
    func2(mp);
    return 0;
}

As you see, I have two functions which do the same job. One uses std::find_if() and the other uses a for loop.

I've seen many codes like func1() after C++11, but from my perspective, std::find_if() uses a lambda so it might have worse performance.

Am I right about this? When should I use one over the other?

I've tried to ask Google but I haven't found anything that can convince me.


Solution

  • Both approaches have the same time complexity of 𝑂(𝑛), but std::find_if() is generally preferred for its clarity. In real-world scenarios, compilers optimize both approaches effectively, so the performance difference is often negligible.