Practical difference of Python, Java, and C++

Array:
Python: a = [1, 2] # list
Java: int a[] = new int[]{1, 2};
C++: vector<int> a = {1, 2};

Set:
Python: s = set([1, 2]) # Python set is unordered; relies on __hash__().
Java: Set<Integer> s = new HashSet<>(Arrays.asList(1, 2)); // Unordered.
Java: Set<Integer> s = new TreeSet<>(Arrays.asList(1, 2)); // Ordered.
C++: set<int> s = {1, 2}; // Ordered; requires less<>.
C++: unordered_set<int> s = {1, 2}; // Unordered; requires hash<>.

Map:
Python: m = dict(a=1, b=2)
Java: Map<String, Integer> m = new HashMap<>() // No good initializer.
C++: map<string, int> m = {{“a”, 1}, {“b”, 2}}; // Ordered.

NULL:
Python: None
Java: null
C++: nullptr

Namespace:
Python: taken from module path (package is directory, module is file)
Java: package x.y; (must match with the path)
C++: namespace x {}

Accessing Other Modules:
Python: import x.y
Java: no need of import
C++: #include <>

Accessing Other Modules with Short Name:
Python: from x.y import z
Java: import x.y.Z;
C++: using namespace x; // Everything in x becomes accessible.

Exception:
Python: try/except/else/finally, raise Exception()
Java: try/catch()/finally, throw(new Exception())
C++: try/catch/throw new Exception()

Function Object:
Python: def function and return it
Java: use anonymous inner class
C++: std::function (function pointer, functor, lambda)

Closure:
Python: return lambda arg: captured + arg
Java: no
C++: return [captured](arg) { return captured + arg; };

Currying:
Python: use lambda
Java: no
C++: auto f1 = std::bind(f0, _1, _2, val, std::cref(val)); // Or use lambda.

Atomic:
Python: ?
Java: AtomicBoolean
C++: std::atomic<bool>

Mutex:
Python: threading.Lock() or threading.RLock()
Java: Lock mutex = new ReentrantLock(true);
C++: std::mutex or std::recursive_mutex

RAII lock:
Python: with threading.Lock() as lock:
Java: synchronozed // Reentrant.
C++: std::lock_guard<std::mutex> l(mutex);

Unicode:
Python: str is Unicode
Java: char is 16-bit (UTF-16)
C++: wchar16_t u”” for (UTF-16), wchar32_t U”” (UTF-32)

Advertisements