array class with sort

hello I am trying to learn how to make an array of classes and initializing them.
 avatar
unknown
c_cpp
2 years ago
1.1 kB
5
Indexable
#include <iostream>
#include <string>
#include <algorithm>
#include <array>

class myclass
{
    int id;
    std::string text;
public:
    myclass() = default;
    myclass(std::string const &a, int i) : id(i), text(a) {}

    bool operator<(myclass const &other) {
        return text < other.text;
    }

    friend std::ostream &operator << (std::ostream &os, myclass const &m) {
        return std::cout << m.text << "\n";
    }
    
    friend bool comp (myclass const & a, myclass const & b);
};

bool comp (myclass const & a, myclass const & b)
{
    return a.id < b.id;
}

int main()
{
    std::array<myclass,4> myobject;
    std::string word;
    int num{0};
    for(int i=0; i < myobject.size(); i++)
    {
        std::cout << "Enter a string: ";
        std::cin >> word;
        std::cout << "Enter a number: ";
        std::cin >> num;
        std::cout << '\n';
        myobject[i] = {word,num};
        
    }
    
    std::sort(myobject.begin(), myobject.end(), comp);
    
    for (auto const &o : myobject)
        std::cout << o;
    
    return 0;
    
}
Editor is loading...