所以我有以下代码可以在 vector 中“搜索”对象的字符串。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
struct migObj
{
migObj(const std::string& a_name, const std::string& a_location) : name(a_name), location(a_location) {}
std::string name;
std::string location;
};
int main()
{
typedef std::vector<migObj> migVec;
migVec v;
v.push_back(migObj("fred", "belfast"));
v.push_back(migObj("ivor", "london"));
// Search by name.
const std::string name_to_find = "ivor";
auto i = std::find_if(v.begin(), v.end(), [&](const migObj& obj) { return name_to_find == obj.name;});
if (i != v.end())
{
std::cout << i->name << ", " << i->location << "\n";
}
return 0;
}
commecnt“按名称搜索”下方的代码负责此结果。我想要做的是制作一个方法,该方法要么添加到 std::vector 中,要么添加到 typedef migVec 中,这样我就可以调用
v.myNewSearchFunction("ivor");
最佳答案
你不能那样做:C++ 没有类似于 C# 中的扩展方法。
您可以从 vector 派生您的类,但是您必须更改所有客户端代码。此外,正如 Roddy 指出的那样,std::vector 没有虚拟析构函数,因此从中派生通常不是一个好主意。
IMO,编写一个简单的函数会是更好的选择。额外的好处是它也适用于大多数其他容器(例如 std::list
)并且与 STL 中的大多数算法更兼容,这些算法通常也是自由函数。
所以你会用这个代替:
myNewSearchFunction(v, "ivor"); // instead of v.myNewSearchFunction("ivor");
在内部,此函数执行 std::find_if(v.begin(), v.end(), ...
。
顺便说一句,请注意使用 std::begin(v), std::end(v)
比 v.begin(), v.end( )
。这使您可以在例如数组。
将事物放入类中 isn't always the best choice in C++ .
关于c++ - 向 std::vector 或 typedef 添加自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16812606/