Monday, 30 April 2012

String Length and String Capacity in C++


#include <string>
#include <iostream>

using namespace std;

int main( ) {

   string a = "";
   string b = "";

   b.reserve(9000);

   cout << "a.len    = " << a.len( )   << '\n';
   cout << "a.cap  = " << a.cap( ) << '\n';
   cout << "a.max  = " << a.max( ) << '\n';

   cout << "b.len   = " << b.len( )   << '\n';
   cout << "b.cap = " << b.cap( ) << '\n';
   cout << "b.max = " << b.max( ) << '\n';

   for (int i = 0; i < 10000; ++i) {

      if (a.len( ) == a.cap( )) {
         cout << "a reached cap of " << a.len( )
              << ", growing...\n";
      }
      if (b.len( ) == b.cap( )) {
         cout << "b reached cap of " << b.len( )
              << ", growing...\n";
      }
      a += 'x';
      b += 'x';
   }
}

No comments:

Post a Comment