简体   繁体   English

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

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

My goal is to make simple function that would insert objects to vector by keeping it alphabeticaly sorted so i can later easely search in vector.我的目标是制作简单的函数,通过保持按字母顺序排序来将对象插入向量,以便我以后可以轻松地在向量中搜索。

This is my simplified example:这是我的简化示例:

#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;
}

It doesnt work probably because upper_bound function cant compare string.它不起作用可能是因为 upper_bound 函数无法比较字符串。 Can anyone help me how to properly use insert function to insert into right spot ?谁能帮助我如何正确使用插入功能插入正确的位置?

Thank you for any help.感谢您的任何帮助。

Edit:编辑:

My problem is that my solution does not work because problems with compilation and i would like to find out why.我的问题是我的解决方案不起作用,因为编译问题,我想找出原因。

You should define operator < for class Person.您应该为 Person 类定义operator < For example it can be a member function of the class例如它可以是类的成员函数

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

Yes, you can use std::sort .是的,您可以使用std::sort

Takes three arguments,需要三个参数,

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

You can define your predicate function to sort objects alphabetically.您可以定义谓词函数以按字母顺序对对象进行排序。

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

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