#include
#include
#include
using namespace std;
void output_item( const string& s )
{
cout << s << '\n';
}
int main( )
{
string next;
vector< string > items;
while( cout << "\n> ", getline( cin, next ) )
{
if( next.empty( ) )
continue;
string::size_type pos = next.find( ' ' );
string cmd( next.substr( 0, pos ) );
string extra;
if( pos != string::npos )
extra = next.substr( pos + 1 );
if( cmd == "quit" || cmd == "exit" )
break;
else if( cmd == "sort" )
sort( items.begin( ), items.end( ) );
else if( cmd == "list" )
for_each( items.begin( ), items.end( ), output_item );
else if( cmd == "add" )
{
if( !extra.empty( ) )
items.push_back( extra );
}
else if( cmd == "clear" )
items.clear( );
else
cout << "unknown command: " << next << endl;
}
}
A vector is a "dynamic array" (so it can grow in size and be re-sized). New items can easily be added to this container via "push_back" (it does not implement a "push_front" as it cannot do this efficiently although you can use the "insert" function to achieve the same result).
The STL algos sort and for_each used in this sample are typical in that they use iterators rather than operating on the container itself (a fundamental difference between the STL and many other libraries that offer similar functionality).
So in under 50 lines we now have a console program that displays a prompt and will execute commands that apply to a dynamic array of items.