问题
最近遇到个问题,即明显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效率会高些,无容器拷贝等耗时操作。