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

标签 c++ vector iterator substring multimap

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

相关文章:

c++ - 使用 Spirit 将 std::vector<std::vector<double> 解析为结构体属性

c# - 如何在 C# 中创建类型化的 IEnumerable?

c++ - 如何从实际函数中推导出 `std::function` 参数?

c++ - 使用 time() 函数计算执行时间

c++ - 在 C++ 中使用 const 的正确方法是什么?

c++ - 当整数类型转换为浮点类型时,C++ 中会发生什么,反之亦然?

c++ - 在 C++ 中使用集合 vector 时出现段错误

具有最快 "Exists"查找的 C++ 容器( vector/数组/等)

c++ - 搜索 vector 中的一系列记录

c++ - Visual C++ 中与 reverse_iterator 相关的崩溃。是合法代码吗?