STL正确使用find_if()打印奇数

STL correct use of find_if() to print out odd numbers

本文关键字:打印 if find STL      更新时间:2023-10-16

如何使用STL中的find_if算法从向量中查找并打印奇数?

让我给你举一个我正在谈论的例子:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool isOdd(int x)
{
    return x%2 == 0;
}
int main(void)
{
    int tab[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    vector<int> myVec(tab, tab + sizeof(tab)/sizeof(tab[0]));
    vector<int>::iterator it;
    // Printing out all numbers
    cout << "Vector contains the following numbers: " << endl;
    for(it = myVec.begin(), it != myVec.end(), ++it)
    {
        cout << *it << ' ';
    }
    // An unsuccessful attempt to print out odd numbers while using find_if and while loop
    vector<int>::iterator bound = find_if(myVec.begin(), myVec.end(), isOdd);
    while(bound != myVec.end())
    {
       cout << *bound << ' ';
    }
 }

while循环有什么问题?我想这是我代码的核心问题。

我正在为find_if函数返回给迭代器的内容赋值,然后我根本不知道如何从向量中挑选奇值;(

问题是您没有在循环中推进迭代器:

while(bound != myVec.end())
{
    cout << *bound << ' '; 
    bound = find_if(bound+1, myVec.end(), isOdd);
}

在C++11中,可以使用std::next(bound)而不是bound+1

此外,当数字为偶数时,您的isOdd会返回true。应该是

bool isOdd(int x) 
{ 
   return x%2 != 0; 
} 

演示。

只是补充一下,对于这个用途,我只使用std::copy_if:

std::copy_if(myVec.begin(), myVec.end(), 
             std::ostream_iterator<int>(std::cout, " "), isOdd);

类似地,代码中的第一个for循环(应该是分号,而不是逗号)可以替换为std::copy:

std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, " "));

演示。