Hey pals, Recently I have been dabbling with Arrays in C++ and many times felt Python has better inbuilt list functions than CPP.If you have felt the same way then this post might change it.After extensive searching in the internet I found out that most of the list functions available in python can be acheived in CPP by using the Vector and Algorithm header files properly.
Here I am sharing few of the CPP versions of commonly used Python List funcitons.
1.Define a list
python
1
l1=[1,2,3,4]
cpp
1 |
|
2.Print
python
1
2
l1=[1,2,3,4]
print(l1)
cpp
1 |
|
3.Length
python
1
2
l1=[1,2,3,4]
l=len(l1)
cpp
1 |
|
4.Clear
python
1
2
l1=[1,2,3,4]
l1.clear();
cpp
1 |
|
5.Add element to the last
python
1
2
l1=[1,2,3,4]
l1.append(5)
cpp
1 |
|
6.Sort the list
python
1
2
3
l1=[1,2,3,4]
l1.sort() # ascending sort
l1.sort(reverse=True) # descending sort
cpp
1 |
|
7.Count the frequency of an element
python
1
2
3
l1=[1,1,2,3,4]
c=l1.count(1);
print(c)
cpp
1 |
|
8.Insert
python
1
2
3
l1=[1,3,4]
c=l1.insert(1,2);
print(c)
cpp
1 |
|
9.Join two lists
python
1
2
3
4
l1=[1,2,3,4]
l2=[5,6,7]
l1=l1+l2
print(l1)
cpp
1 |
|
10.Join list elements as string
python
1
2
l1=[1,2,3,4]
c=" ".join(map(str,l1))
cpp
1 |
|
Happy coding !!