CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2006
    Posts
    1

    help me understand strings?

    im starting to get confused. i would appriciate it if someone could help me with my noobish understandings...

    1. when do i use string::size_type vs using the iterator for string?

    for example, i would like to examine each character in a string. therefore i would do something like

    int index = 0;
    while ( index < mystring.size)
    {
    cout << mystring.at(stringindex);
    }


    now i could also print out each character in a string via the iterator?

    for(myiterator = st1.begin(); myiterator != st1.end(); myiterator ++)
    {
    if( *myiterator == 'h')
    {
    do something
    }
    }

    ///////

    i guess when to find out the size or length or get what is in a particular space in a string, use the size_t....when using a string function, use the iterator???

  2. #2
    Join Date
    Jun 2002
    Location
    Germany
    Posts
    1,557

    Re: help me understand strings?

    bbq,

    This is a very rich topic.

    I believe that most developers tend to avoid the use of iterators for strings. Recall that the std::string, much like the std::vector<T>, offers a clean indexing operator. In addition, std::string has the member function at(...).

    It might be wise at first to avoid using iterators for std::string's and simply, until a clearer understanding has been reached, use the size_type combined with size(...) as well as operator[](...) and/or at(...).

    The power of iterators comes with template such as std::list<T>.

    P.S. Do not forget the parentheses in the call to mystring.size().

    Sincerely, Chris.
    Last edited by dude_1967; March 6th, 2006 at 03:55 PM. Reason: Improved clarity
    You're gonna go blind staring into that box all day.

  3. #3
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: help me understand strings?

    Using iterators is preferable for a couple of reasons:
    Code is more generic, so you can use any other container instead of the std::string.
    It may be faster (especially it may reduce the number of indirection needed to access a character).

    However, if it makes the code look less pretty, or if you fear errors, you can use indexes.

    For indexes, you should not use int, but std::string::size_type.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured