使用equal_to函数对象在向量中查找字符串

find strings in vector with equal_to function object

本文关键字:向量 查找 字符串 对象 equal to 函数 使用      更新时间:2023-10-16

我有以下代码:

#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算法。