You are not logged in. Please login at www.codechef.com to post your questions!

×

find function not working (in vector)

After trying a lot I'm still not able to figure out why its not being able to find if reverse of the word being searched for exists in the vector already or not. Here is the problem link : https://www.hackerearth.com/problem/algorithm/password-1/ Here is the code

#include <bits/stdc++.h>
using namespace std;

string rev(string s) //Function to reverse string
{
    string ans=" ";
    for(int i=s.length();i>=0;i--)
    ans = ans + s[i];
    return ans;
}
char print(string x)// Function that Returns the character at the middle position of a given string
{
    return x[(x.length()-1)/2]; 
} 
int main()
{
        int n;
        cin>>n;
        vector<string>v;
        string str;
        for(int i=0;i<n;i++)
        {
        cin>>str;
        v.push_back(str);
        }
        for(int i=0;i<n;i++)
        {
        if(find(v.begin(),v.end(),rev(v[i]))!=v.end()) // String found yo
        {
        int len = v[i].length();
        cout<<len<<" "<<print(v[i])<<endl;
        break;
        }
        }
    return 0;
}

Alternatively ideone link : http://ideone.com/e7T0FL

Thanks for reading :)

asked 03 Jul '15, 01:19

h1ashdr%40gon's gravatar image

3★h1ashdr@gon
2912319
accept rate: 10%


The basic correction :

string rev(string s) //Function to reverse string
{
    string ans=""; // remove the space
    for(int i=s.length()-1;i>=0;i--)  // i = s.length() is wrong, the last index is s.length()-1
    ans = ans + s[i];
    return ans;
}

If at any point you are unsure of what the last position is, use rbegin() for iteration (complimented by r.end() ). Look it up on the c++ reference for details.

link

answered 03 Jul '15, 04:59

thezodiac1994's gravatar image

6★thezodiac1994
1.0k61122
accept rate: 16%

edited 03 Jul '15, 05:04

Well I guess that was a stupid mistake! Thanks alot :) Are there any suggestions you have on this code?

(03 Jul '15, 12:23) h1ashdr@gon3★
toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×630
×393
×72
×68
×29
×7
×3

question asked: 03 Jul '15, 01:19

question was seen: 1,133 times

last updated: 03 Jul '15, 12:32