Vector of objects in C++

How do I make an object vector using c++? And how do I sort this vector of objects, for example, using some sort algorithm (quicksort, mergesort, shellsort or radixsort)?

#include <iostream>   
using namespace std;

class Game {
public:
float preco;
char nome[25];
int idade;
char categoria[30];

};

int main (){
Game *jogo = new Game();
int i;

//for (i=0; i < 2; i++){
cout <<"Digite o preço do jogo: \n";
cin >> jogo->preco;
cout <<"Digite a nome do jogo: \n";
cin >> jogo->nome;
cout <<"Digite a idade indicativa para joga-lo : \n";
cin >> jogo->idade;
cout <<"Qual a categoria do jogo: \n";
cin >> jogo->categoria;
//}

cout << jogo->preco <<"\n";
cout << jogo->nome << "\n";
cout << jogo->idade << "\n";
cout << jogo->categoria << "\n";


return 0;   

}
Author: Jefferson Quesado, 2017-06-06

2 answers

1. Use the library that C++ offers you.

Your code looks like C, Not c++. You can use the STL to make your code simpler and clearer.

2. "using std namespace" is bad practice.

When you write using namespace std, you are importing the entire std into the global namespace and this can cause conflicts with another library.

3. You do not need to use pointers to create variables

Using pointers is unnecessary in your case, then, if you don't deallocate it using delete, you can have a memory Leak.

4. Are you making a mess of languages

Write your code in English to make it more elegant and less confusing. And if you do not know English, do not be lazy to learn.


The code should be rewritten like this:

#include <string>
#include <iostream>   

struct Game {
    float price;
    std::string name;
    int min_age;
    std::string category;
};

int main (){
    Game game;

    std::cout << "Digite o preço do jogo: " << std::endl;
    std::cin >> game.price;
    std::cout << "Digite a nome do jogo: " << std::endl;
    std::cin >> game.name;
    std::cout << "Digite a idade indicativa para joga-lo: " << std::endl;
    std::cin >> game.min_age;
    std::cout << "Qual a categoria do jogo: " << std::endl;
    std::cin >> game.category;

    std::cout << game.price << std::endl;
    std::cout << game.name << std::endl;
    std::cout << game.min_age << std::endl;
    std::cout << game.category << std::endl;

    std::cin.get();

    return 0;   

}

Even if this is not what you want, you can do what you want from these good practices.

 1
Author: xninja, 2018-09-06 00:41:59

For each position in the Array you must create a new object and insert in the appropriate position. And to sort, choose one of the class attributes as a name or age to serve as the sort index.

 0
Author: ed1rac, 2017-06-07 05:49:13