question on two lines of code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gdarian216
    New Member
    • Oct 2006
    • 57

    question on two lines of code

    I was trying to read this code and see what it does and I know it is a fuction to a bigger code and is passed some arguments I just had a couple of questions. the first one is temp part of the language since they didn't declare it and the part of the code in bold im not sure what those lines do. Can anyone help

    string::size_ty pe loc;
    if(loc==string: :npos);



    Code:
    vector<string> split(const string& temp, char s)
    {
      string find;
      vector<string> _find;
      [B]string::size_type loc;[/B]
      for(int i=0,j=0;i<temp.size(); i++)
        {
            find.clear();
            loc = temp.find(s,i);
    
          [B]if(loc==string::npos)[/B]
                return _find;
    
            while(j!=loc)
              {
                find += temp[j];
                j++;
              }
            i += j;
    
           _find.push_back(find);
        }
       return _find;
    }
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    string::size_ty pe loc;//This variable represent current location in the string
    if(loc==string: :npos);//You might wont to see this

    Savage

    Comment

    • gsi
      New Member
      • Jul 2007
      • 51

      #3
      Hi,
      size_t is defined in <cstddef>. It is typically used to represent size in bytes, so defined as an unsigned integral type. This is preferred over 'int' data type bcos of the bigger values it can represent (Unsigned).

      string::npos is a static member constant which is of 'unsigned' integral type. It is assigned a value of ' -1' . hence it wraps around to give you the maximum value that could be represented using an unsigned integral type. It is returned by the find member function of the std::string class to indicate a failiure (Absence of a match you are requesting).

      eg.
      [code = cpp]
      string::size_ty pe loc;
      if(loc==string: :npos);
      [/code]

      In this two lines of code, the author is trying to figure out if the return value from the find member function is whether a valid position or a failiure.

      Thanks,
      Gsi.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by gdarian216
        string::size_ty pe loc;
        if(loc==string: :npos);
        A size_type is a typedef of a size_t which is a typedef of an unsigned int.

        So loc is just an unsigned int.

        string::npos is peculiar to std::string. It represents a number larger than any possible string. Usually (but not always, it is -1). Many of the string methods use string::npos to indicate not found in searches.

        Comment

        Working...