Python to C ++ conversion

2

I work on my course with C ++, and wanted to use a Python class variable access feature. Here's an example:

class Telefone:
    nums = {}

    def __init__(self, numero):
        self.num = numero
        Telefone.nums[numero] = self
        print(list(Telefone.nums))


joao = Telefone(40028922)  
paulo = Telefone(30302020)  
pedro = Telefone(55677655)  

Output:

[40028922]
[40028922, 30302020]
[40028922, 30302020, 55677655]

How do I do this in C ++?

    
asked by anonymous 11.06.2017 / 20:30

1 answer

1

I think there is no simple way to implement this in C ++. Certain features of languages such as Python can only be expressed in C ++ with complicated hacks or logic. But you could do so:

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;


class Telefone
{
    using num_map = unordered_map<string, Telefone>;

    static num_map nums;

public:
     Telefone()  { }

    Telefone(const string& numero)
    {
        nums[numero] = *this;
         Print();
    }

    void Print()
    {
        cout << "[ ";
        for (const auto& num : nums)
            cout << num.first << " ";
        cout << "]\n";
    }
};

Telefone::num_map Telefone::nums;


int main()
{
    Telefone joao("40028922");
    Telefone epaulo("30302020");
    Telefone pedro("55677655");

    std::getchar();
    return 0;
}

If I were you, I would try to write this in a simpler way using C ++ features rather than trying to imitate Python behavior. Note: I have used string to represent the number because the Visual C ++ hash table implementation (% w / o%) fails to keep the order of values with integers.

    
13.06.2017 / 08:25