Showing posts with label STL. Show all posts
Showing posts with label STL. Show all posts

Wednesday, May 11, 2011

STL list iterator example c++

An example showing how to use STL list iterator. A STL list iterator is used to specify the location in the list where an items will be inserted or deleted. [STL list iterator]

#include <iostream.h>
#include <list>
void print(list <char> );// elsewhere
main()
{ list <char> l;
list <char>::iterator p;
l.push_back('o'); l.push_back('a'); l.push_back('t');
p=l.begin();
cout <<" "<< *p<<endl;  // p refers to the 'o' in ('o', 'a', 't')
print(l);
l.insert(p, 'c');
// l is now ('c', 'o', 'a', 't') and p still refers to 'o'
cout <<" "<< *p<<endl;
print(l);
l.erase(p);
cout <<" "<< *p<<endl; // p refers to an 'o' but it is not in l!
print(l);
l.erase(l.begin()); //removes front of l
print(l);
}

STL vector sorting example

Here's a simple STL vector sorting example code in c++. a vector container is sorted by using sort() from <algorithm>, . It just traverses the items in a given STL list container.
[STL vector sorting example]

//Sorting a vector with 9 integers
#include <iostream.h>
#include <vector>
#include <algorithm>
void print( vector<int> ) ;//utility function outputs a $container
int main()
{
vector<int> a;
// Place 9,8,7,6,5,4,3,2,1 into the vector
for(int i=0; i<9;++i)
a.push_back(9-i);// put new element after all the others
print(a); // elements of a are (9,8,7,6,5,4,3,2,1)
sort( a.begin(), a.end() ); //in the STL <algorithm> library
print(a); // elements are nor in order.
}
 
void print( vector<int> a)
{
for(vector<int>::iterator ai=a.begin(); ai!=a.end(); ++ai)
cout << *ai << " ";
cout << endl;
cout << "----------------"<<endl;
}

STL list iterator example

Here's a simple STL list iterator example code in c++. It just traverses the items in a given STL list container. [STL list iterator example]

An Example of Iterating Through a List

void print( list<int> a)
{
for(list<int>::iterator ai=a.begin(); ai!=a.end(); ++ai)
cout << *ai << " ";
cout << endl;
cout << "----------------"<<endl;
}

STL stack example c++ objc

Here's a simple STL stack example code in c++. It just reverses a string using a STL stack object. [STL stack example]

void reverse(string & x)
//Afterwards x will have the same elements in the opposite order.
{
stack<char> s;
const int n = x.length();
//Put characters from x onto the stack
for(int i=0; i<n; ++i)
s.push(x[i]);
//take characters off of stack and put them back into x
for(int i=0; !s.empty(); ++i, s.pop())
x[i]=s.top();
}