简体   繁体   English

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

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

How can I possibly make use of find_if algorithm from STL to find and print out odd numbers from vector. 我怎么可能利用STL中的find_if算法从向量中查找并打印出奇数。

Let me just give you an example of what I'm on about: 让我给你一个关于我正在做的事的例子:

#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 unsuccesful 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 << ' '; 
 } 


 }

What is wrong with while loop, I guess it's the core problem of my code. while循环有什么问题,我想这是我代码的核心问题。 I'm assigning whatever find_if function will return to iterator, and than I simply can't figure out how to cherry pick odd values from vector ;( 我正在分配任何将返回到迭代器的find_if函数,而且比我根本想不出如何从vector;(

The problem is that you are not advancing the iterator in your loop: 问题是您没有在循环中推进迭代器:

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

In C++11 you can use std::next(bound) instead of bound+1 . 在C ++ 11中,可以使用std::next(bound)代替bound+1

Also, your isOdd returns true when the number is even. 同样,当数字为偶数时, isOdd将返回true It should be 它应该是

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

Demo. 演示

Just adding that for this use I'd just use std::copy_if : 只需为此添加,我将使用std::copy_if

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

Similarly, the first for loop in your code (and those should be semicolons, not commas) can be replaced with std::copy : 类似地,代码中的第一个for循环(应该是分号,而不是逗号)可以用std::copy代替:

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

Demo . 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM