我正在尝试在我的应用程序中创建搜索功能。如果用户输入一个子字符串(或完整字符串),我想知道该子字符串是否与存储在我的 vector 中的任何字符串或部分字符串匹配。
目前已编写以下代码:
cout << "Input word to search for: ";
cin >> searchString;
for (multimap <string, vector<string> >::const_iterator it = contactInformationMultimap.cbegin(); it != contactInformationMultimap.cend(); ++it)
{
for (vector<string>::const_iterator iter = it->second.cbegin(); iter != it->second.cend(); ++iter)
{
if (*iter.find(searchString))
^^^^^^^^^^^^^^^^^^^^^^^ this does not work, if i cout *iter it is the correct word stored in the vector. The problem is that i can not use the find function.
}
}
大家有什么建议吗?
最佳答案
一元运算符的优先级低于后缀运算符。在 if 语句中,您需要在成员访问运算符之前评估一元运算符 * 。所以你必须写
if ( ( *iter ).find(searchString) != std::string::npos )
或者你可以写
if ( iter->find(searchString) != std::string::npos )
考虑到此记录
if ( ( *iter ).find(searchString) )
没有任何意义。
你也可以写
for (multimap <string, vector<string> >::const_iterator it = contactInformationMultimap.cbegin(); it != contactInformationMultimap.cend(); ++it)
{
for ( const std::string &s : it->second )
{
if ( s.find(searchString ) != std::string::npos ) /*...*/;
}
}
关于c++ - 使用迭代器从 vector 中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27627461/