gpt4 book ai didi

c++ - 使用迭代器从 vector 中查找子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:23:02 24 4
gpt4 key购买 nike

我正在尝试在我的应用程序中添加搜索功能。如果用户输入一个子字符串(或完整的字符串),我想知道该子字符串是否与存储在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com