c 在std :: vector中搜索
C++ search in an std::vector
说我有这样的向量:
vector< pair<string, pair<int, int> > > cont;
现在,我希望在cont
中找到其first
等于"ABC"
的Elem。如何使用STL为我们提供的函数和算法轻松执行此操作(find_if,is_equal ??)。(请不要提升,也没有新的C 。)
编辑:是否可以在不定义谓词函数的情况下进行?
之类的东西
typedef std::pair<std::string, std::pair<int, int> > pair_t;
struct Predicate : public std::unary_function<pair_t, bool>
{
public:
Predicate(const std::string& s):value(s) { }
result_type operator () (const argument_type& pair)
{
return pair.first == value;
}
private:
std::string value;
};
std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
Predicate("ABC"));
或lambda,如果C 11。
auto pos = std::find_if(cont.begin(), cont.end(),
[](const std::pair<std::string, std::pair<int, int>>& pair)
{
return pair.first == "ABC";
});
确实,没有结构。
有一种不好的方法。typedef std::pair<std::string, std::pair<int, int> > pair_t;
namespace std {
template<>
bool operator ==<> (const pair_t& first, const pair_t& second)
{
return first.first == second.first;
}
}
std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
std::bind2nd(std::equal_to<pair_t>(), std::make_pair("ABC", std::make_pair(1, 2))));
如果您需要的速度比O(N)
搜索快,则可以替换vector
使用map
(或平行添加) O(log N)
搜索(或使用unordered_map
的O(1)
),不需要函数:
vector<pair<string, pair<int,int>>> cont {{"ABC",{1,11}}, {"DFG",{2,22}}};
map <string, pair<int,int>> M(cont.begin(), cont.end());
cout << M["ABC"] << endl;
使用RO库(可耻的插头),这将只是:
#include <sto/sto.h>
using namespace sto;
...
auto it = cont / (_0=="ABC");
此处/
OVERAPARED OP OP,该OP在内部调用find_if
;_0
-引用Sto Lambda表达式中元素(或对)的第一个元素;_0=="ABC"
-LAMBDA表达式生成find_if
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- 有根的二进制搜索树.保留与其父级的链接
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- 如何从 std::vector 搜索和返回项目
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- c 在std :: vector中搜索
- 使用std::vector将数组的最佳匹配搜索到矩阵中
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 在搜索字符串时,Vector下标超出了范围
- 检查在vector的vector中搜索时std::find是否失败
- 可视化 如何在 c++ 中搜索 vector<Object*> 中的特定变量?
- 在vector<std::p air<int, vector > >中搜索<int>
- 在Vector中搜索字符串
- 在std::vector中搜索和计数特定元素的最快方法是什么?
- 从c++中的特定索引中搜索Vector的元素