【问题标题】:Inserting values of class to ordered Linked list - C++将类的值插入到有序链表 - C++
【发布时间】:2015-04-27 19:31:29
【问题描述】:

我有 Info 类,在 main.cpp 中,我想创建使用 Info 类型的有序链表实现的对象,例如 orderedLinkedList<Info> object1;

能否解释一下如何插入值(名字、姓氏和出生年份)。

#ifndef _INFO_H
#define _INFO_H

#include <iostream>
#include <string>

class Info{

    private:
        std::string _first_name;
        std::string _last_name; 
        int _birth_year;

    public:
        Info()=default;
        ~Info()=default;
        Info(string first_name, string last_name, int birth_year) : _first_name(first_name), _last_name(last_name), _birth_year(birth_year) {}

        string fName() {return _first_name;}
        string lName() {return _last_name;}
        int bYear() {return _birth_year;}

        void setInfo(string first_name, string last_name, int birth_year);          


};

void Info::setInfo(string first_name, string last_name, int birth_year)
{
    _first_name = first_name;
    _last_name = last_name;
    _birth_year = birth_year;
}

#endif

【问题讨论】:

  • 你的意思是 forward_list 吗?

标签: list class c++11 linked-list


【解决方案1】:

您的问题存在多个问题。

STL 中没有有序链表这种东西。如果你的结构和展示的一样小,我会advise against 使用链表。

然后你可以使用例如std::vector(你仍然需要自己的实现来保持它的排序)或者更好的std::set,它已经实现了排序行为并且通常渐近优于向量/列表(O(log(n))对于std::setO(n) 对于std::vector)。为了使您的Info 类在std::set 中可用,您必须实现其小于运算符(在这种情况下签名为bool Info::operator&lt;(const Info &amp;rhs))。

顺便说一句,不要使用带有前导下划线的名称,因为它们在 C++ 中是保留的。 (尾随下划线很好。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多