繁体   English   中英

按字母顺序将对象插入向量 C++

[英]Insert object to vector in alphabetical order c++

我的目标是制作简单的函数,通过保持按字母顺序排序来将对象插入向量,以便我以后可以轻松地在向量中搜索。

这是我的简化示例:

#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 函数无法比较字符串。 谁能帮助我如何正确使用插入功能插入正确的位置?

感谢您的任何帮助。

编辑:

我的问题是我的解决方案不起作用,因为编译问题,我想找出原因。

您应该为 Person 类定义operator < 例如它可以是类的成员函数

struct Person {
    bool operator <( const pserson &rhs ) const { return ( name < rhs.name ); }
    string name;
};

是的,您可以使用std::sort

需要三个参数,

Sort(your_vector.begin(),your_vector.end(),predicate)

您可以定义谓词函数以按字母顺序对对象进行排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM