Repository navigation
Expand file tree
/
Copy path07-03-cross-reference.cpp
More file actions
84 lines (74 loc) · 2 KB
/
Copy path07-03-cross-reference.cpp
File metadata and controls
84 lines (74 loc) · 2 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
79
80
81
82
83
84
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <cctype>
#include <sstream>
// 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;
}
typedef std::map<std::string, std::vector<int> > Xref;
Xref xref(std::istream& in,
std::vector<std::string> find_words(const std::string&) = split)
{
using namespace std;
string line;
int line_number = 0;
Xref 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) {
vector<int>& lines = ret[*it];
if(find(lines.begin(), lines.end(), line_number) == lines.end())
lines.push_back(line_number);
}
}
return ret;
}
int main()
{
using namespace std;
Xref ret = xref(cin);
// write results
for(Xref::const_iterator it = ret.begin();
it != ret.end(); ++it) {
stringstream ss;
pair<const string, vector<int> > p = *it;
ss << p.first << " : ";
vector<int>::const_iterator line_it = p.second.begin();
ss << *line_it; ++line_it;
while(line_it != p.second.end()) {
ss << ", "; ss << *line_it;
++line_it;
}
string out = ss.str();
if(out.size() >= 77) {out.resize(76); out+="...";}
cout << out << endl;
}
return 0;
}