Python to C++ conversion

Asked

Viewed 865 times

2

I work on my course with C++, and wanted to use a Python class variable access feature. See 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)  

Exit:

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

How do I do it in C++?

  • I don’t understand - you want a feature similar to the one demonstrated in c++?

  • You can use this: Shred Skin which is a python compiler for c++; I hope I helped

  • @Blogger, yes, I wanted to do something similar in c++

1 answer

1


I think there is no simple way to implement this in C++. Certain languages like Python can only be expressed in C++ with hacks or complicated logics. 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 correctly instead of trying to mimic Python’s behavior. Note: I used string to represent the number because the Visual C hash table implementation++(std::unordered_map) failed to maintain order of integer values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.