c++ - 按字母顺序将对象插入 vector C++

标签 c++ vector operator-overloading overloading

我的目标是制作一个简单的函数,通过保持对象按字母顺序排序将对象插入 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/

相关文章:

c++ - 为什么 operator< 应该是非成员函数?

C++11 向后兼容性

c++ - 我怎样才能知道我的源代码的编译日期?

c# - 如何使用 P/Invoke 将 MemoryStream 数据传递给非托管 C++ DLL

c++ - 在 macOS 上使用 Boost 测试 detect_memory_leaks 选项

c++ - 从结构 vector 中选择随机结构

vector - 如何在 Clojure 中展平嵌套向量?

文件和 vector 的 C++ 长度

c++ - 修改/访问矩阵内容 C++

c++ - 内部类模板的非成员运算符重载