Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [C++] Why use the STL? A quick example
Index -> Programming, C++ -> C++ Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Wed Aug 04, 2004 10:23 pm   Post subject: [C++] Why use the STL? A quick example

So, let's say you want to remove all bad characters (to be defined) from a string. First we'll look at the problem solved without the STL, then taking advantage of it.

For both examples we'll want a function which can test to see if a character matches what we'll consider a "bad" character.

code:
bool bad_char(char source)
{
   // return true if the character is the letter o.
   return (source == 'o');
}


Now, without the STL:

code:
#include <string>
#include <sstream>
#include <iostream>

bool bad_char(char source)
{
   // return true if the character is the letter o.
   return (source == 'o');
}

int main()
{
   std::string original_string = "Hello world";
   std::stringstream new_string_buffer;

   for (int i = 0; i < original_string.length(); i++)
   {
      if (!bad_char(original_string[i]))
      {
                  new_string_buffer << original_string[i];
          }
   }

   std::string new_string = new_string_buffer.str();

   std::cout << "original: " << original_string << std::endl
             << "new:      " << new_string      << std::endl;
}


And with the STL:

code:
#include <string>
#include <algorithm>
#include <iostream>

bool bad_char(char source)
{
   // return true if the character is the letter o.
   return (source == 'o');
}

int main()
{
        std::string original_string = "Hello world!", new_string;

        std::remove_copy_if(original_string.begin(),
                            original_string.end(),
                            std::back_inserter(new_string),
                            bad_char);

    std::cout << "original: " << original_string << std::endl
              << "new:      " << new_string      << std::endl;
}
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, C++ -> C++ Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: