Pages

Sunday, June 5, 2016

Read List Containers in C++

List in c++ are implemented as doubly-linked list as opposed to vectors which are implemented as dynamic arrays. As a property of doubly-linked list, list cannot be accessed with index location as we can with arrays and vectors.


To iterate through a list we need to define iterators as follows:

#include     // std::cout
#include       // std::list
using namespace std;

int main () {

list<int> mylist = {1,45,32,12,67};
list<int>::iterator it =  mylist.begin();

  for(;it != mylist.end();it++){
 cout << "\n" << *it;
  }
 return 0;
}

Sorting in C++

sort method defined under algorithm header file can be used to sort arrays and vectors.
#include

1. Sorting char and int array:

The input parameters to sort char and integer array are pointers to beginning and end of array.


char mychar[] = {'z','q','-','e','a'};
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

int myint[] = {'100','34','45','23','12'};
int length = sizeof(mychar)/sizeof(int);
sort(mychar, mychar+length);

It can also be used to sort strings defined as character arrays.

char mychar[] = "back";
int length = sizeof(mychar)/sizeof(char);
sort(mychar, mychar+length);

The output will be "abck"

2. Sorting vectors:

Similar to arrays, vectors can be sorted using sort method by passing pointers to begin and end of vector.

vector<int> myvector = {'z','q','-','e','a'};
sort(myvector.begin(),myvector.end());

Return value of the method is void as it alerts the containers or arrays directly through pointers.