Thread: can anyone tell me why this outputs backwards

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    4

    can anyone tell me why this outputs backwards

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    
    vector<string> store_all_substrings(string s)
    {
       
       if(s.length() <= 1)
       {
         vector<string> single_letter;
          single_letter.push_back(s);
          return single_letter;
       }
        vector<string> all_substrings = store_all_substrings(s.substr(1)); 
       for (int i = 1; i <= s.length(); i++)
        all_substrings.push_back(s.substr(0, i));
         
       return all_substrings;
    }
    
    int main()
    {
    
      vector<string> all_substrings = store_all_substrings("cat");
      for(int i = 0; i < all_substrings.size(); i++)
         cout << all_substrings[i] << "\n";
       
       return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It prints out in the order you build the vector. If that's not the order you want to print them, then either (a) build the vector in the opposite order (b) use reverse to reverse the vector (c) pick a container that supports push_front instead.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    I think his problem is that the strings generated in:
    Code:
    store_all_substrings(s.substr(1));
    Are stored before the substrings of the current string.

    Honestly, I'd make the prototype:
    Code:
    void store_all_substrings(vector<string> &result, const string &s)
    To make it faster and easier to read, as you don't have to copy as much from vector to vector; all you have to do is push_back.

    But the actual problem is that you "store all substrings" of s.substr(1) before you generate the substrings of "s". If you wanted it reversed, first do the substrings of s and then the other thing.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Print backwards? Can someone please help me?
    By matthayzon89 in forum C Programming
    Replies: 11
    Last Post: 04-23-2010, 07:30 AM
  2. why i getting different outputs?
    By nkrao123@gmail. in forum C Programming
    Replies: 2
    Last Post: 12-08-2009, 08:33 AM
  3. Backwards uint16_t?
    By DavidDobson in forum C Programming
    Replies: 7
    Last Post: 05-11-2009, 09:45 AM
  4. Taking input and Outputting it backwards
    By whtpirate in forum C Programming
    Replies: 9
    Last Post: 06-08-2003, 10:59 AM
  5. how to print a string backwards
    By Unregistered in forum C# Programming
    Replies: 2
    Last Post: 01-27-2002, 01:04 PM