使用equal_to函数对象在向量中查找字符串
find strings in vector with equal_to function object
我有以下代码:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <functional>
using namespace std;
typedef istream_iterator<string> is_it;
typedef vector<string>::iterator v_str_it;
int main()
{
int i = 4;
ifstream ifstr("1.txt");
is_it ifstrm(ifstr);
is_it eof;
vector<string> v_str(ifstrm, eof);
v_str_it vsit = v_str.begin();
while( (vsit = find_if(vsit, v_str.end(),
bind2nd(equal_to<string>(), i ))) != v_str.end())
{
cout << *vsit << endl;
++vsit;
}
return 0;
}
据我所知,在find_if(vsit, v_str.end(), bind2nd(equal_to<string>(), i )
中,我应该像使用"sometext"
一样使用const char
,而不是使用int i
。但是我怎样才能找到长度等于4的单词呢?我很困惑,需要一些建议。
find_if
将只返回序列中满足谓词的第一项。
对于这个,你真的想要一个lambda,如果你使用的是C++11。这看起来像:
[](std::string const& x) { return x.size() == i; }
(不确定确切的语法)。
要创建一个"函子",这在这里是最简单的:
struct CompareStringLength
{
int len_;
explicit CompareStringLength( int len ) : len_(len)
{
}
bool operator()(std::string const& str ) const
{
return str.size() == len_;
}
};
在您的矢量中,您现在将使用std::find_if( v.begin(), v.end(), CompareStringLength(i) )
;
以获得第一个元素。要找到所有这些,没有std::copy_if
可以将它们复制到另一个向量中,因此您实际上必须创建一个返回相反结果的不同谓词,并使用存在的remove_copy_if或编写自己的copy_if算法。
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 以C++递归方式查找向量中的最大值
- C++如何在向量中查找最常见的元素
- 查找两个排序向量中共有的元素
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- 在对向量中查找元素的索引
- 在C++中查找两个向量之间最相似的值
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 在无法访问向量的情况下查找迭代器的末尾
- C++ 查找字符串中存在的元素向量
- 在结构向量中查找最接近的值
- 查找多个向量之间的公共元素(无整数元素)
- 如何修复错误:使用向量查找最小值和最大值进行合并排序
- 在C++的向量中查找值
- 在每个向量<向量中查找最小/最大 x,y<Point>>
- 查找 2D 向量的位置,该向量是类C++的一个元素
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法
- 如何使用向量查找平均值和标准差
- 使用向量查找公共元素的问题
- C++向量 - 查找 ( "no match for 'operator =='" )