0

my question is: is it possible to create a multitype stl set? If a want to calculate the occurrences number from a text file, how can I do? I need to use only or ...

#include <set>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main()
{
    set<string, int> danteh;
    set<string>::iterator iterator_danteh;
    ifstream d1("text.txt");
    ofstream d2("output.txt");
    string word;
    while(!d1.eof())
    {
        d1 >> word;
        danteh.insert(word);

    }

    cout << endl;
    cout << "FINE!";
    return 0;
}
  • 1
    You likely want to use a std::map instead (Also: Do not test streams for eof, but for a successfule extraction) –  Jul 12 '14 at 12:58

2 Answers2

1

Use std::map from <map> header, like:

std::map< std::string, int > danteh ;  // Key is the std::string, 
                                       //  value is the int

For counting words , simply use following logic :

while ( d1 >> word ) // Extract word from stream
{
   danteh[word]++;   // Add into map and increment the count
}

For iterating through map, use iterators as you use it for set, difference is first (key) will give you the word as second(value) will give you its frequency.

P0W
  • 46,614
  • 9
  • 72
  • 119
0

You can use a std::multiset instead of the std::set. multiset is defined in the same header:

#include <set>

As the name suggests, the difference between set and multiset is that the multiset can contain multiple copies of the same value.

Inserting the strings works just like with the set you used before:

std::multiset<std::string> danteh;
...
while(!d1.eof())
{
    d1 >> word;
    danteh.insert(word);
}

Once the set is built, you can retrieve the occurrence count of a given word with:

danteh.count("hello");
Reto Koradi
  • 53,228
  • 8
  • 93
  • 133