C++ 在 vector 中查找

标签 c++ stl vector iterator find

我正在尝试做一个函数,该函数将返回在 vector 中发现事件的位置。但我的返回值始终为 0,我确信存在匹配项。

代码如下:

int findInItemvector(vector<Item> vec, string name)
{
    for(vector<Item>::iterator it = vec.begin(); it < vec.end(); it++)
    {
        if(it->getName() == name)
        {
            return it - vec.begin(); 
            break;
        }
        else
        {
            return 0;
        }

    }
}

最佳答案

当您的第一个元素不匹配时,else 分支将执行 return,这将离开该函数,并且您的循环的其余部分不会被执行。你想要这样的东西:

int findInItemvector(vector<Item> vec, string name)
{
    for(vector<Item>::iterator it = vec.begin(); it < vec.end(); it++)
    {
        if(it->getName() == name)
        {
            return it - vec.begin(); 
        }
    }

    return 0;
}

但是,由于第一项也可以匹配(在这种情况下 it - vec.begin() == 0),我建议您使用其他保护值,例如 -1(永远不可能是有效的 vector 索引)。

关于C++ 在 vector 中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6809608/

相关文章:

c - 从秒开始的快速时间结构

c++ - 按 vector 对中的索引删除元素

c++ - 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?

c++ - STL映射查找第一个不可重复的字符

C++ STL 比较映射找不到(运算符==)

c++ - 在不初始化数据的情况下调整 C++ std::vector<char> 的大小

带有对象指针的 C++ vector push_back

c++ - 为什么 C++11 中仍然需要 "using"指令来从基类中引入在派生类中重载的方法

c++ - C++单继承的内存布局和这个C代码一样吗?

c++ - 使用 Visual Studio 2013 编译 FFTW 3.3.4