CPP version of Python List functions

Python

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:


l1=[1,2,3,4]

C++:

#include <vector>

using namespace std;

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


2.Print


Python:


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

C++:

#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:

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

C++:

#include <vector>

using namespace std;

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


4.Clear


Python:

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

C++:

#include <vector>

using namespace std;

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


5.Add element to the last


Python:

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

C++:

#include <vector>

using namespace std;

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


6.Sort the list


Python:

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

C++:

#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:

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


C++:

#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:

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


C++:

#include <vector>

using namespace std;

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


9.Join two lists


Python:

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

C++:

#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:

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

C++:

#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 !!