| ID | CS001098 | Creation date | September 16, 2008 |
| Platform | S60 3rd Edition, FP2 | Tested on devices | Nokia 6220 Classic |
| Category | Open C/C++ | Subcategory | Files/Data |
| Keywords (APIs, classes, methods, functions): vector, list, sort(), list.sort() |
This code snippet shows how to use the C++ Standard Template Library (STL) sort function with predefined data types. The sort function needs at least two parameters: start and end. These iterator parameters are used to sort the range of elements between them. An optional third parameter has the default less-than operator as a value to compare elements.
Some STL containers cannot use regular the sort function and they provide specialized versions of sort as a member function. The list container is one of them and it also has an optional default value to compare elements.
Note: In order to use this code, you need to install the Open C/C++ plug-in.
This snippet can be self-signed.
The following libraries are required:
LIBRARY libstdcpp.lib
LIBRARY libc.lib
LIBRARY euser.lib
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <string>
using namespace std;
bool exampleCompare(string& s1, string& s2)
{
// compare string lengths
int len1 = s1.length();
int len2 = s2.length();
return len1 < len2;
}
int main()
{
//-- Sorting predefined data types --
// 1) int array
int intArray[] = { 3, 1, 2 };
int arrayElements = sizeof(intArray) / sizeof(intArray[0]);
sort(intArray, intArray + arrayElements);
for (int i=0; i<arrayElements; ++i)
cout << intArray[i] << ' '; //1 2 3
// 2) int vector
vector<int> intVector;
intVector.push_back(3);
intVector.push_back(1);
intVector.push_back(2);
int vectorElements = intVector.size();
sort(intVector.begin(), intVector.end());
for (int i=0; i<vectorElements; ++i)
cout << intVector[i] << ' '; //1 2 3
// 3) string list
list<string> stringList;
list<string>::iterator stringIterator;
stringList.push_back ("second");
stringList.push_back ("first");
stringList.push_back ("third");
stringList.sort();
for (stringIterator = stringList.begin();
stringIterator != stringList.end();
++stringIterator)
cout << *stringIterator << ' '; //first second third
//use function exampleCompare to sort list again
stringList.sort(exampleCompare);
for (stringIterator = stringList.begin();
stringIterator != stringList.end();
++stringIterator)
cout << *stringIterator << ' '; //first third second
return 0;
}
The STL sort function is used to sort arrays, vectors, and lists and the sorted values are displayed on the screen.