Question

The code tries to figure out if two strings have the same pattern.

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>


bool findMatch(char * s1, char * s2){
    std::map<char, std::string> words;
    std::istringstream iss(s1);
    std::string word;
    //for (std::string::size_t i = 0; i < s2.size(); ++i)      //line 1
    //for (int i = 0; i < s2.size(); ++i)                      //line 2
    {
        if (!(iss >> word))
            return false; 
        std::string& mapping = words[s2[i]];
        if (mapping == "")
            mapping = word; 
        else if (mapping != word)
            return false; 
    }
    return !(iss >> word); 
}

int main(int argc, char * argv[]){
    bool b = findMatch("red blue blue red red yellow", "abbaac");
    std::cout << b << std::endl;
    return 0;
}

Questions: I had two tries, line 1 and line 2, neither of them worked

line 1, Error: class "..." has no member "size_t"

line 2: Error: char * s2 Expression must have class type

Any ideas?

Was it helpful?

Solution

You're inconsistent a bit. You use char* and use std::strings as well, std::string has the benefit of having the size method that you are using in the for loop. std::string doesn't have std::string::size_t, it's either size_t or std::string::size_type.

I'd replace your char* parameters to const std::string&, that way it works as you intended.

OTHER TIPS

There are at least a few problems, size_t is not part of string and s2 is not std::string so you need to use something like strlen:

for (size_t i = 0; i < strlen(s2); ++i)

which means you need to include cstring

#include <cstring>     

and for consistency sake it probably makes more sense to use std::string in place of char *.

Try changing line 1 to

for (size_t i = 0; i < strlen(s2); ++i)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top