对谓词使用std::find
using std::find with a predicate
我想使用std::find
函数以及谓词(不确定我是否使用正确的单词)。下面是代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class foo {
public:
typedef pair< int, vector<int> > way;
typedef pair< int, int > index;
typedef pair< index, vector<way> > entry;
vector< entry > table;
void bar()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
way w = make_pair( 1, v1 );
vector<way> v2;
v2.push_back(w);
index id = make_pair( 10, 20 );
entry en = make_pair( id, v2 );
table.push_back( en );
}
void insert()
{
index new_id = make_pair( 10, 20 );
if ( find(table.begin(), table.end(), new_id) != table.end() ) {
// index matched in the table
// then I will push back a new pair (way)
// to the second part of the entry
}
}
};
int main()
{
foo f;
f.bar();
f.insert();
return 0;
}
可以看到,find()
应该根据每个条目中的第一个元素搜索table
。现在,它说==
没有重载来比较pair
。
你想要std::find_if
:
...
if(find_if(table.begin(), table.end(), [&new_id](const entry &arg) {
return arg.first == new_id; }) != ...)
EDIT:如果你没有c++ 11(因此没有lambda),你必须创建一个自定义函子(函数或函数对象)来比较entry::first
和搜索的index
:
struct index_equal : std::unary_function<entry,bool>
{
index_equal(const index &idx) : idx_(idx) {}
bool operator()(const entry &arg) const { return arg.first == idx_; }
const index &idx_;
};
...
if(find_if(table.begin(), table.end(), index_equal(new_id)) != ...)
EDIT:由于index
只是一对int
,您也可以通过值而不是const引用来捕获它,以保持代码更清晰,更简洁,但这也无关紧要。
在c++ 11中,还可以使用std::any_of
if (std::any_of(table.cbegin(), table.cend(),
[&new_id](const entry &arg) { return arg.first == new_id; }))
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 为什么在向量上使用 std::find() 时会出现错误?
- 使用 std::find 时没有匹配的函数调用错误
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- STL std::find() C++
- 如何将 std::find() 与 2d std: 数组一起使用?
- 为什么 std::find( s.begin(), s.end(), val ) 比集合 s 的 s.find(val) 慢 1000 倍<int>?
- 如果迭代器没有因插入而无效,则使用std::find和C::insert()是线程安全的
- 未按值排序的std::find和std::any_of
- 为什么std::map有find成员函数
- 在libc++和libstdc++之间的std::map上使用std::find时的实现差异
- 有没有办法在Cython中导入std::find find_if等?
- std::map::find 的效率是否与值的数据大小有关?
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 使用 find() 通过 std::set 的迭代器将不起作用。出了什么问题?
- Android-NDK 的 GGC/C++ 对于 std::string::find/std::getline(...) 来说似乎不稳定
- MinGW g++ cannot find std::stof
- 如何将std::find/std::find_if用于自定义类对象的向量