forked from orazaro/accelerated
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07-00-cross-reference.cpp
More file actions
78 lines (70 loc) · 1.87 KB
/
07-00-cross-reference.cpp
File metadata and controls
78 lines (70 loc) · 1.87 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <cctype>
// isspace is overloaded so we use wrapper function as argument for find_if
inline bool space(char c)
{
return isspace(c);
}
inline bool not_space(char c)
{
return !isspace(c);
}
std::vector<std::string> split(const std::string& str)
{
typedef std::string::const_iterator iter;
std::vector<std::string> ret;
iter i = str.begin();
while(i != str.end())
{
// ignore leading spaces
i = find_if(i, str.end(), not_space);
// find end of next word
iter j = find_if(i, str.end(), space);
if(i != str.end())
ret.push_back(std::string(i, j));
i = j;
}
return ret;
}
std::map<std::string, std::vector<int> >
xref(std::istream& in,
std::vector<std::string> find_words(const std::string&) = split)
{
using namespace std;
string line;
int line_number = 0;
map<string, vector<int> > ret;
while(getline(in, line)) {
++line_number;
vector<string> words = find_words(line);
for(vector<string>::const_iterator it = words.begin();
it != words.end(); ++it)
ret[*it].push_back(line_number);
}
return ret;
}
int main()
{
using namespace std;
map<string, vector<int> > ret = xref(cin);
// write results
for(map<string, vector<int> >::const_iterator it = ret.begin();
it != ret.end(); ++it) {
pair<const string, vector<int> > p = *it;
string w("line");
if(p.second.size() > 1)
w += "s";
cout << p.first << " occurs on " << w << ": ";
vector<int>::const_iterator line_it = p.second.begin();
cout << *line_it; ++line_it;
while(line_it != p.second.end()) {
cout << ", " << *line_it;
++line_it;
}
cout << endl;
}
return 0;
}