×
Namespaces

Variants
Actions

Sorting predefined types using STL sort in Open C++

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Nokia 6220 Classic
Compatibility
Platform(s): S60 3rd Edition, FP2
Article
Keywords: vector, list, sort(), list.sort()
Created: aknyman (03 Sep 2008)
Last edited: hamishwillee (05 Jul 2012)

Contents

Overview

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.

MMP file

The following libraries are required:

LIBRARY libstdcpp.lib
LIBRARY libc.lib
LIBRARY euser.lib

Source file

#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;
}

Postconditions

The STL sort function is used to sort arrays, vectors, and lists and the sorted values are displayed on the screen.

See also

Sorting class and struct types using STL sort in Open C++

This page was last modified on 5 July 2012, at 06:27.
92 page views in the last 30 days.