Reputation: 38
I am working on a project to read a Context-free Grammar and represent it 1.Vectorial, 2. Branched chained lists, 3. Array (Table). I encounter a problem with string comparison. When I read a string from keyboard representing right side of a Production rule, I want to check if that string exists in a vector of strings. The problem is that comparison is not working right. If the string I compare is the first string from the vector of strings than the comparison is working fine. But if the string I compare is a string from the vector of strings other than first comparison is not working, it's like the string is not from the vector of strings. Sorry for my English. I better let the code explain
bool is(string &s, vector<string> &v) {
for (auto i : v) {
return (i.compare(s)==0) ? true : false;
}
}
This function returns true only if s=v[0], otherwise returns false even if s=v[2]
Upvotes: 0
Views: 624
Reputation: 105
To do that you'd have to loop into the vector with a for loop and compare every string in it, it would be something like:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool doExists(string s, vector<string> v) {
for (int i=0;i<v.size();i++) {
if (s.compare(v[i]) == 0) {
return true;
}
}
return false;
}
int main(){
vector<string> phrases = {"Hello!", "I like potatos!","I like fries.","How are you today?","I'm good.","Hello!"};
int helloLocated = doExists("Hello!", phrases);
cout << helloLocated;
}
The console would print 1.
Upvotes: 1