Vector of objects in C ++

0

How do I make an object vector using c ++? And how do I sort this array 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;   

}
    
asked by anonymous 07.06.2017 / 01:05

2 answers

1

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

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

2. "using namespace std" is a bad practice.

When you type using namespace std , you are importing all std to 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, because if you do not deallocate it using delete , you can have a Memory Leak .

4. You are 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;   

}

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

    
29.08.2018 / 19:37
0

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

    
07.06.2017 / 07:49