Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iterator>
- #include <fstream>
- #include <map>
- #include <vector>
- #include <string>
- using index_type = std::map<std::string, std::vector<std::string>>;
- bool AppendToIndex(index_type& index, std::string filename) {
- std::ifstream file(filename);
- if (!file.is_open())
- return false;
- while (!file.eof()) {
- std::string word;
- file >> word;
- auto inserted = index.insert({word, {filename}});
- if (!inserted.second)
- inserted.first->second.push_back(filename);
- }
- return true;
- }
- int main() {
- index_type index{};
- for (auto s : {"file1.txt", "file2.txt", "file3.txt"}) {
- if (!AppendToIndex(index, s))
- std::cout << "Warning: could not open " << s << "!\n";
- }
- std::string line;
- while (true) {
- std::cout << "Enter a word to search or hit return to exit: ";
- if (!std::getline(std::cin, line) || line.empty())
- break;
- auto pos = index.find(line);
- if (pos == index.end())
- std::cout << "Word was found in none of the files!\n";
- else {
- std::cout << "Word was found in: {";
- std::copy(pos->second.begin(), pos->second.end(),
- std::ostream_iterator<std::string>(std::cout, ", "));
- std::cout << "\b\b}\n";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement