I am making a program that finds how many anagrams does a line contain for homework and I have a problem. My program is not entering a simple "for" loop. I've been reading whole evening and I cannot understand what is the problem. I've put 7 control cout-s to see where exactly does it enter and where not. Results are - 1, 2, 3 ,7 - not even entering the "for" loop. What could be the problem? Here is my code:
#include<iostream>
#include<string>
#include <sstream>
#include<vector>
#include <algorithm>
using namespace std;
bool isAnagram(string x, string y)
{
vector<char>v;
int szX = x.size(), szY = y.size();
for (int i = 0; i < szX; i++)
{
if (!(find(v.begin(), v.end(), x[i]) != v.end()))
{
v.push_back(x[i]);
}
}
for (int j = 0; j < szY; j++)
{
if (!(find(v.begin(), v.end(), y[j]) != v.end()))
{
return false;
}
}
return true;
}
void breakStringToWords(string str, vector<string> w)
{
istringstream ss(str);
string word;
while (ss >> word)
{
w.push_back(word);
}
}
int main()
{
string x;
vector<string>v;
int cnt=0,sz;
while(getline(cin, x))
{
if(x=="")
{
return 0;
}
cout<<1<<endl;
breakStringToWords(x, v);
cout<<2<<endl;
sz=v.size();
cout<<3<<endl;
for(int i=0; i<sz; i++)
{
cout<<4<<endl;
if (isAnagram(v[i - 1], v[i]))
{
cout<<5<<endl;
cnt++;
}
cout<<6<<endl;
}
cout<<7<<endl;
cout<<cnt<<endl;
}
return 0;
}
Thank you in advance!
Re:
It entered the loop and threw another exception
when i is 0, you are accessing v[-1]
:
for(int i=0; i<sz; i++)
{
cout<<4<<endl;
if (isAnagram(v[i - 1], v[i]))