【发布时间】:2015-10-02 05:46:31
【问题描述】:
我写了一个基于类的向量:
class A {
private:
string b;
string c;
public:
A(string n, string l) { b = l ;c = n; }
struct Finder {
Finder(std::string const& n) : name(n) { }
bool operator () ( const A & el) const { return el.b == name; }
private:
std::string name;
};
};
int main()
{
vector<A> a1;
a1.push_back(A("AA","aa"));
a1.push_back(A("BB","bb"));
a1.push_back(A("CC","cc"));
a1.push_back(A("DD","dd"));
vector<string>::iterator it;
it = find_if(a1.begin(), a1.end(), A::Finder("CC"));
if (it != a1.end()) {
auto pos = it - a1.begin();
cout << "CC is found at " << pos ;
}
}
现在,我想在 a1 中搜索一个值。假设我想找到发生“CC”的元素的索引。
我找到了这些类似的解决方案:
Search a vector of objects by object attribute
How can I find an object in a vector based on class properties?
How to find an object with specific field values in a std::set?
当我实现本节中的所有 cmets 时,我仍然得到错误!我错过了什么?我想问题在于定义 vector::iterator it;
错误 C2679:二进制“=”:未找到采用“std::_Vector_iterator<_myvec>”类型右侧操作数的运算符(或没有可接受的转换)
和,
错误 C2678: 二进制 '!=' : 未找到采用 'std::_Vector_iterator<_myvec>' 类型的左侧操作数的运算符(或没有可接受的转换)
【问题讨论】:
-
在发布错误消息时,您应该真正指出编译器指向的行,否则我们必须猜测。
-
std::[multi]map<std::string, std::string>在这里不是更有意义吗?
标签: c++ class object vector find