tox*_*e20 5 c++ typedef 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;
}
Run Code Online (Sandbox Code Playgroud)
纪念"按名称搜索"下方的代码负责此结果.我想要做的是创建一个方法,可以添加到std :: vector或typedef migVec,所以我可以调用
v.myNewSearchFunction("ivor");
Run Code Online (Sandbox Code Playgroud)
你不能这样做:C++没有类似于你在C#中的扩展方法.
您可以从vector派生您的类,但是您必须更改所有客户端代码.此外,正如Roddy所指出的那样,std :: vector没有虚拟析构函数,所以从中推导它通常是一个坏主意.
IMO,编写一个简单的函数将是更好的选择.另外的好处是它也可以用于大多数其他容器(例如std::list)并且与STL中的大多数算法更兼容,这些算法通常也是自由功能.
所以你会改为:
myNewSearchFunction(v, "ivor"); // instead of v.myNewSearchFunction("ivor");
Run Code Online (Sandbox Code Playgroud)
在内部,这个功能可以std::find_if(v.begin(), v.end(), ....
顺便说一句,请注意,使用它会std::begin(v), std::end(v)比使用更好v.begin(), v.end().这使您可以在例如数组上运行相同的代码.
将内容放入类中并不总是C++中的最佳选择.