Data Structure in Python and C++
Size
Python | C++ |
---|---|
len(x) |
x.empty() |
x.size() |
Stack
Python | C++ |
---|---|
s = list() |
std::stack<int> s; |
s.append(x) |
s.push(x); |
yyy = s.pop() |
s.pop(); |
s[-1] |
s.top(); |
Queue
Python | C++ | |
---|---|---|
Queue | q = collections.deque() |
std::queue<int> q; |
q.append() |
q.push(xxx); |
|
x = q.popleft() |
q.pop(); |
|
q[0] |
q.front(); |
|
Queue (thread safe) | q = Queue.Queue() |
|
q.put(xxx) |
||
yyy = q.get() |
||
q.queue[0] |
Priority Queue
Python | C++ | |
---|---|---|
Priority queue | q = list() # smallest on top |
std::priority_queue<T> q; // largest on top |
heapq.heappush(q, x) |
q.push(x); |
|
y = heapq.heappop(q) |
q.pop(); |
|
q[0] |
q.top(); |
|
Priority queue (thread safe) | q = Queue.PriorityQueue() |
|
q.put(x) |
||
yyy = q.get() |
||
q.queue[0] |
Hash Map
Python | C++ |
---|---|
d=dict() |
std::unordered_map<k_type,v_type> d; |
key in d |
d.find(key) ! = d.end(); |
d[key] |
d[key]; |
d[key] = value # change or insert |
d[key] = value; // change or insert |
for k, v in d.items(): |
for (auto iter:d) {iter->first; iter->second;} |
for key in d: |
|
del d[key]; # or d.pop(key) |
d.erase(key); d.erase(iter); |
Hash Set
Python | C++ |
---|---|
s=set() |
std::unordered_set<int> s; |
item in s |
s.find(item) ! = d.end(); |
s.add(item) |
s.insert(item) |
s.remove(item) # item has to be in |
|
s.discard(item) # item can be not in |
s.erase(item) // item can be not in s |
for x in set |
for (auto& x:s) {x;} |
s1.union(s2); s1 | s2 |
|
s1.intersection(s2); s1 & s2 |
|
s1.difference(s2); s1 - s2 |