-1

The problem is like this: Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2. EX: Input: a1= arp, live, strong. a2 = lively, alive, harp, sharp, armstrong. Returns arp, live, strong.

I have the following class and when I compile the code I get the error "error: no matching member function for call to 'push_back' ". And I just can't figure out what is the problem.

PS: The class and declaration of the member function are given and I must solve the problem using them as they are.

class WhichAreIn {
public:
    static std::vector<std::string> inArray(std::vector<std::string>& array1, std::vector<std::string>& array2);
};
std::vector<std::string> WhichAreIn::inArray(std::vector<std::string>& array1, std::vector<std::string>& array2)
{
    int lengthArray1 = size(array1);
    std::vector<std::string> r; //resulting string
    for (int i = lengthArray1; i > 0; i--) {
        auto matchFound = find(array2.begin(), array2.end(), array1[i]);
        r.push_back(matchFound);
        break;
    }
    return r;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
Maria
  • 71
  • 10

1 Answers1

1

matchFound is an iterator which must be dereferenced.

for(int i=lengthArray1;i>0;i--){
  auto matchFound= find(array2.begin(), array2.end(), array1[i]);
  if (matchFound != array2.end()) {
    r.push_back(*matchFound);
    break;
  }
}
Surt
  • 15,501
  • 3
  • 23
  • 39
  • Rookie mistake. I've corrected it but now an exception is thrown: Caught std::exception, what(): basic_string::_M_construct null not valid. Any thoughts on what might be throwing this exception? – Maria Nov 09 '20 at 19:59
  • An iterator needs to have a useful value, see update. – Surt Nov 09 '20 at 20:01
  • Not sure that break is needed here - OP does not need a vector then and can return single string – Slava Nov 17 '20 at 05:20
  • @Slava that likely another error. – Surt Nov 17 '20 at 12:05