Thread: reversing a string

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    56

    reversing a string

    Hello,

    I am trying to learn the C++ standard library and I am having trouble with this program.
    Code:
    //cin with strings
    #include <iostream>
    #include <string>
    #include <vector>
    #include <cstdio>
    using namespace std;
    
    vector<string> reverse(const string& s)
    {
    	vector<string> return_s;
    	typedef string::size_type string_size;
    	string_size i = 0;
    	
    	for(i = s.size() - 1; i > 0; i--)//Here is the problem
    		return_s.push_back(s.substr(i, 1));
    	
    	return return_s;
    }
    
    int main ()
    {
    	string s;
    	vector<string> v;
    	cout << "Enter a string: " << endl;
    	
    	while(getline(cin, s))
    		v = reverse(s);
    		
    	cout << "Your string in reverse: " << endl;		
    	for(vector<string>::size_type i = 0; i < v.size(); i++)
    		cout << v[i];
    	cout << endl;
    		
    	return 0;
    }
    In the indicated for loop, if I change the middle part to i >= 0, then I get an error for being out of range. If i doesn't go to 0 then it doesn't take the last character. Why do I get an out of range error for going to 0? Any suggestions?

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    string::size_type is an unsigned integer, so decrementing past zero yields a positive number.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    You're using a vector of strings to hold an array of chars. string is an array of chars. In the spirit of "learning the standard library," you can avoid the loops altogether.
    Code:
    std::string reverse(const std::string & s)
    {
       std::string ret( s.size(), char() );
       std::reverse_copy( s.begin(), s.end(), ret.begin() );
       return ret;
    }
     //Then just use strings in main()
    Last edited by CodeMonkey; 06-13-2009 at 12:16 PM. Reason: stupidity
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    56
    Sebastiani, I changed string::size_type to int and the program now runs as I expect it. CodeMonkey, can you explain what the first two lines after the first brace are doing? I'm not sure I understand them. Thanks for the help.

  5. #5
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    Sure. The first line creates a temporary string to hold the value you wish to return. The initializer says to make it the same size as s, and full of char(). It doesn't matter what it's filled with.
    The second line copies the range s.begin() to s.end() to the range beginning at ret.begin(). But it copies them backwards. So now ret has all of the elements of s, but in reverse order. Then you just return ret.

    *edit*
    One of the beauties of using this method is that is is standard and generic. You can change all of the std::strings to std::vector<long double>s, and the code will work the same way.
    Even more generally, functions in the family of reverse_copy() (STL algorithms), can operate with any object that acts like an "iterator" (i.e. that is an iterator). So, instead of iterating through predefined iterator types, like in string and vector, you could use a low-level pointer-to-array. It's really neat!
    Last edited by CodeMonkey; 06-13-2009 at 02:27 PM.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    FWIW, such a function could be reduced even further if desired:
    Code:
    std::string reverse(const std::string& s)
    {
        return std::string(s.rbegin(),s.rend());
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    That's much better. Hardly need the function, then, except for clarity.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  5. Reversing a String
    By ToasterPas in forum C++ Programming
    Replies: 10
    Last Post: 08-14-2001, 12:20 PM