迭代器范围错误导致std:find查找失败

问题

最近遇到个问题,即明显Jack在列表中,std::find就是无法查询到。
bug代码如下:

#include <iostream>
#include <vector>
#include <string>
class Base {
public:
    Base (std::initializer_list<std::string> strs) {
        for (const auto& str : strs) {
            m_names.push_back(str);
        }
    };

    std::vector<std::string> GetNames() { 
        return m_names;
    };
private:
    std::vector<std::string> m_names;
};

int main() {
    Base filter = {"Tom", "Jack", "Nick"}; 
    std::string str = "Jack";
    auto res = std::find(filter.GetNames().begin(), filter.GetNames().end(), str);
    
    if (res == filter.GetNames().end()) {
        std::cout << str <<" not found" << std::endl;
    } else {
        std::cout << "found name:"<< *res << std::endl;
    }
    return 0;
}

运行时总是无法找到"Jack"字符串,但有时候又能走到else分支,但输出并不是"Jack",这是为什么?

分析

问题在于类成员函数GetNames()返回的是m_names的拷贝,在std::find中调用了2次,产生2个m_names的拷贝,此时begin()和end()并不是同一个容器的迭代器,从而导致查找失败。

解决

将GetNames()返回m_names的常量引用或者直接拷贝处理单独保存。
1.修改为返回常量引用

std::vector<std::string> GetNames();

修该为:

const std::vector<std::string>& GetNames();

2.直接拷贝单独保存:

int main() {
    Base filter = {"Tom", "Jack", "Nick"}; 
    std::string str = "Jack";
    auto names = filter.GetNames(); // 拷贝出来单独保存
    auto res = std::find(names .begin(), names.end(), str);
    
    if (res == names.end()) {
        std::cout << str <<" not found" << std::endl;
    } else {
        std::cout << "found name:"<< *res << std::endl;
    }
    return 0;
}

综合比较,方案1效率会高些,无容器拷贝等耗时操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值