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

list
1
l1=[1,2,3,4]

cpp

vector
1
2
3
4
5
6
7
8
#include <vector>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
}

2.Print

python

list
1
2
l1=[1,2,3,4]
print(l1)

cpp

vector
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
 copy(v1.begin(),v1.end(),ostream_iterator<int>(cout," "));
}

3.Length

python

list
1
2
l1=[1,2,3,4]
l=len(l1)

cpp

vector
1
2
3
4
5
6
7
8
9
#include <vector>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
 int i=v1.size();
}

4.Clear

python

list
1
2
l1=[1,2,3,4]
l1.clear();

cpp

vector
1
2
3
4
5
6
7
8
9
#include <vector>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
 v1.clear();
}

5.Add element to the last

python

list
1
2
l1=[1,2,3,4]
l1.append(5)

cpp

vector
1
2
3
4
5
6
7
8
9
#include <vector>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
 v1.push_back(5);
}

6.Sort the list

python

list
1
2
3
l1=[1,2,3,4]
l1.sort() # ascending sort
l1.sort(reverse=True) # descending sort

cpp

vector
1
2
3
4
5
6
7
8
9
10
11
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
 vector<int> v1{1,2,3,4};
 sort(v1.begin(),v1.end()); // ascending sort
 sort(v1.begin(),v1.end(),greater<int>()); // descending sort
}

7.Count the frequency of an element

python

list
1
2
3
l1=[1,1,2,3,4]
c=l1.count(1);
print(c)

cpp

vector
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
 vector <int> v1{1,1,2,3,4};
 int c=count(v1.begin(),v1.end(),1);
 cout<<c<<endl;
}

8.Insert

python

list
1
2
3
l1=[1,3,4]
c=l1.insert(1,2);
print(c)

cpp

vector
1
2
3
4
5
6
7
8
9
#include <vector>

using namespace std;

int main()
{
 vector <int> v1{1,3,4};
 v1.insert(v1.begin()+1,2);
}

9.Join two lists

python

list
1
2
3
4
l1=[1,2,3,4]
l2=[5,6,7]
l1=l1+l2
print(l1)

cpp

vector
1
2
3
4
5
6
7
8
9
#include <vector>

using namespace std;

int main()
{
 vector <int> v1{1,2,3,4},v2{5,6,7};
 v1.insert(v1.end(),v2.begin(),v2.end());
}

10.Join list elements as string

python

list
1
2
l1=[1,2,3,4]
c=" ".join(map(str,l1))

cpp

vector
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
 vector <int> v1{1,2,3,4};
 stringstream ss;
 copy(v1.begin(),v1.end(),ostream_iterator<int>(ss," "));
 cout<<ss.str()<<endl;
}

Happy coding !!