STL正确使用find_if()打印奇数
STL correct use of find_if() to print out odd numbers
如何使用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, " "));
演示。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 为什么这个 IF 语句在循环内不打印
- 我的 if 语句打印在我的 while 循环中的每个 if 语句上,无论它是否为假
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 使用while和if递归打印字符
- 打印此矩阵的 if 语句是什么
- 仅在向量末尾打印新行 - "if"语句在"for"循环之外
- C++ if 语句未按预期工作,在请求输入之前打印"else"
- 用于打印工作人员名称的If语句
- 如何让程序在打印出 while/if 语句之前请求输入字符串"course"
- 为什么在满足if语句之后,else语句仍然打印?
- 你好!我是新的c++和我试图使一个脚本,将打印一个if语句到一个文件
- C++ If/else 打印出两个输出
- 使用"if"打印大写字母