T
T
Timur Tokar2014-11-07 00:19:59
C++ / C#
Timur Tokar, 2014-11-07 00:19:59

Efficient use of STL (C++). How to write a program without using loops?

The essence of the question is how to write a program for reading and replacing words in a file using STL methods without using cycles? Save the end result to a new file while retaining the original formatting of the file.
What to change words with is stored in:
map<string, string> dict;
My assumptions are based on the use of for_each(), find(), getline(), istringstream. But I can't put it all together.
In fact, the program is a training translator.
Here is what I did:

#include <iostream>
#include <iterator>
#include <fstream>
#include <map>

using namespace std;

int main()
{
    /*
     *Тут была реализация чтения файла в map без использования  циклов
     *(К вопросу не относится).
    */
    //В контейнере map содержится key - искомые слова, value - на то что надо
    //заменить при нахождении слова.
    map<string, string> dict((ifstream_pair_iter(read)), ifstream_pair_iter());
    
    return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Misha Krinkin, 2014-11-07
@kmu1990

I think you need to get familiar with istream_iterator, ostream_iterator and transform. Well, probably write one functor.

K
Koss1024, 2014-11-07
@Koss1024

#include <iterator>  // istream_iterator
#include <map>
#include <algorithm> // transform
#include <string>
#include <locale> // tolower

// Input file looks like this:
/* text.txt
You wanna play a little game?
Check this out.
*/

using namespace std;

typedef map<string, string> Vocabulary;
Vocabulary vocabulary;

string translator(string word)
{
   transform(word.begin(), word.end(), tolower); // locase

   Vocabulary::const_iterator trans = vocabulary.find(word);
   return vocabulary.end() != trans ? *trans : word;
}

void translate_file(string fin, string fout, const Vocabulary& vocabulary)
{
   ifstream in(fin);
   ifstream out(fout);

   istream_iterator<string> original_words(in);
   istream_iterator<string> eof;

   ostream_iterator<string> tranlated_words(out, " ");

   transform(original_words, eof, tranlated_words, translator);
}


int main()
{
   
   vocabulary["you"]    = "vy";
   vocabulary["wanna"]  = "hotite";
   vocabulary["game"]   = "igra";
   // ...

   translate_file("text.txt", "translated_text.txt", vocabulary);
   return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question