我的目标是制作一个简单的函数,通过保持对象按字母顺序排序将对象插入 vector ,这样我以后可以轻松地在 vector 中搜索。
这是我的简化示例:
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Names {
public:
Names(void);
~Names(void);
bool Insert(const string & namer);
private:
struct Person {
string name;
};
vector<Person>people;
};
Names::Names() {
};
Names::~Names() {
};
bool Names::Insert(const string& namer) {
Person p;
p.name = namer;
people.insert(upper_bound(people.begin(), people.end(), p), p);
}
int main(int argc, char** argv) {
Names b1;
bool status;
status = b1 . Insert("John Smith");
status = b1 . Insert("Bat Man");
status = b1 . Insert("A Aron");
return 0;
}
它不起作用可能是因为 upper_bound 函数无法比较字符串。谁能帮我如何正确使用插入功能插入正确的位置?
感谢您的帮助。
编辑:
我的问题是我的解决方案不起作用,因为编译有问题,我想找出原因。
最佳答案
你应该定义operator <
对于类人。比如可以是类的成员函数
struct Person {
bool operator <( const pserson &rhs ) const { return ( name < rhs.name ); }
string name;
};
关于c++ - 按字母顺序将对象插入 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22438458/