samedi 28 août 2021

How to define variable and compare value inside if statement?

I have a code snippet like this:

if ((std::vector<int>::iterator iter = std::find(v.begin(), v.end(), i)) != v.end()) 
{
    // ....
}

But the compiler complains on this statement. However, changing my code into

std::vector<int>::iterator iter;
if ((iter = std::find(v.begin(), v.end(), i)) != v.end()) 
{
    // ....
}

Fixes the issue.

So, I was wondering why the first version does not work, and what is the return value of the statement below?

std::vector<int>::iterator iter = std::find(v.begin(), v.end(), i)

Aucun commentaire:

Enregistrer un commentaire