3

What is the error in this code:

    #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct symtab{
  string name;
  string location;
};
vector<symtab> symtab_details;

bool search_symtab(string s){

  if (find (symtab_details.begin(), symtab_details.end(), s)!=symtab_details.end()) return true;
  return false;
}


int main() {

    bool get = search_symtab("ADD");
    return 0;
}

I am getting the following error:

usr/include/c++/4.8.2/bits/stl_algo.h:166:17: error: no match for ‘operator==’ (operand types are ‘symtab’ and ‘const std::basic_string’) if (*__first == __val)

3
  • 2
    The find function tries to find a symtab structure in your vector. Learn about lambda expressions and std::find_if for one way of solving your problem. Commented Mar 31, 2018 at 21:33
  • 1
    overload operator== in your symtab class so that it can be compared to a const std::string & Commented Mar 31, 2018 at 21:35
  • The error is quite clear. If you don't understand why it's an error, please read more about operator overloading before opening questions about it, as it is a pretty fundamental feature of the language. Commented Apr 1, 2018 at 9:19

2 Answers 2

8

You are trying to find a std::string, "ADD", in a std::vector<symtab>. Of course that won't work.

What you need is std::find_if.

auto it = std::find_if(symtab_details.begin(),
                       symtab_details.end(),
                       [&s](symtab const& item) { return item.name == s; });
return  (it != symtab_details.end());
Sign up to request clarification or add additional context in comments.

5 Comments

@Debian_yadav, you need to compile using a C++11 compiler. E.g. if you use g++, you can use -std=c++11 in the command line to compile your program as a C++11 program.
I am using g++ compiler
@Debian_yadav, use -std=c++11 then.
But I am having linker problem in gcc
@Debian_yadav, that was a typo on my part. Use g++ -std=c++11.
3

The code is searching for an object of type symtab that matches an object of type std::string. So you have to provide a comparison operator to tell whether a particular symtab object is equal to a particular std::string object. You need

bool operator==(const symtab&, const std::string&);

If you read the error message carefully that's what it's telling you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.