War*_*tin 1 c++ iterator std find
如果问题很愚蠢,请耐心等待.
以下是在头文件中定义的:
typedef char NAME_T[40];
struct NAME_MAPPING_T
{
NAME_T englishName;
NAME_T frenchName;
};
typedef std::vector<NAME_MAPPING_T> NAMES_DATABASE_T;
Run Code Online (Sandbox Code Playgroud)
后来需要找到一个特定的英文名称:
const NAMES_DATABASE_T *wordsDb;
string str;
std::find_if( wordsDb->begin(),
wordsDb->end(),
[str](const NAME_MAPPING_T &m) -> bool { return strncmp(m.englishName, str.c_str(), sizeof(m.englishName)) == 0; } );
Run Code Online (Sandbox Code Playgroud)
这段代码(我诚实地复制粘贴)编译,但如果我想检查find_if()返回的值,如下所示:
NAMES_DATABASE_T::iterator it;
it = std::find_if(blah ..)
Run Code Online (Sandbox Code Playgroud)
代码不会编译!
实际上,行 = std :: find_if(...) 将返回错误:
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::_Vector_const_iterator<_Myvec>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)
怎么了 ?
谢谢你的时间.
const NAMES_DATABASE_T *wordsDb;
你wordsDb
是const,因此wordsDb->begin()
返回一个const迭代器,因此也find_if
返回一个const迭代器.您试图将该const迭代器分配给非const NAMES_DATABASE_T::iterator it
,因此错误.
您可以使用NAMES_DATABASE_T::const_iterator
获取const迭代器.std::string
除非有一些罕见的情况需要,否则你应该使用而不是那些char缓冲区.