Functor

How would i write a functor for this code.
The code is written to read data from a file and store in a multimap.
The data has numbered lines.
eg:1 This is a string
2 This is a string too

So the aim is to store each word in the line with the number and then to enter a word to search for the line numbers it appears on. I do not know how to go about and write a functor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<iostream>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<map>

using namespace std;

 int main()
 {
     multimap<int, string>myMap;
     ifstream infile("Enter your file here");

     if(!infile)
     {
         cout << "Error: Can't open.\n";
         cout << "Program Terminating.\n";
         exit(EXIT_FAILURE);
     }

     string line;

     while(getline(infile, line, '\n'))
     {
         stringstream ss(line);

         string token;
         string lineNumber;
         string word;

         getline(ss,lineNumber,' ');
            int number = stoi(lineNumber);

         while(getline(ss, token, ' '))
            myMap.insert(pair<int,string>(number,token));
     }

     string enteredWord;
     cout << "Enter the word to search:";
     cin >> enteredWord;

     
     cout << "The word is on line numbers:\n";  //to get the line numbers of the words.
     for(auto it = myMap.begin(); it != myMap.end(); ++it)
     {
         if(it -> second == enteredWord)
            cout <<  it -> first << "\n";
     }
     cout << endl;

     for(auto it = myMap.begin(); it != myMap.end(); ++it)
     {
        cout << it -> first << " ";
        cout << it -> second << " ";
        cout << "\n";
     }
     return 0;
 }
Last edited on
Do you know what a functor is?
yeah i do. Its a comparator or a predicate if bool return type. I am unable to formulate the code.
Not really, it a class that can be called like a function.

It's a class or struct that has operator()(<some args>).

I'll try to lookup an example I've posted previously.

EDIT: Ok, found one. This demonstrates a functor in the context you need, and demonstrates a lambda that does the same thing.
http://www.cplusplus.com/forum/beginner/125212/#msg679337
Last edited on
Thanks kbw.
Topic archived. No new replies allowed.