c++ text file processing

Started by
12 comments, last by snk_kid 19 years, 7 months ago
Here's something I hacked as an exercise to learn STL. The first part reads the data file while the second part just prints the values in the map.

#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <list>
using namespace std;

int main() {
string key, value;
map<string, list<string>* > ht;
ifstream iFile("test.txt");

while (!iFile.eof()) {
iFile >> key >> value;
list<string>* adjacent;
if (ht.find(key) != ht.end()) {
adjacent = ht[key];
} else {
adjacent = new list<string>;
ht.insert(pair<string, list<string>* >(key, adjacent));
}
adjacent->push_back(value);
}

typedef map<string, list<string>* >::const_iterator MapIterator;
typedef list<string>::const_iterator ListIterator;
for (MapIterator m = ht.begin(); m != ht.end(); m++) {
cout << m->first << " ";
list<string>* adjacent = m->second;
for (ListIterator l = adjacent->begin(); l != adjacent->end(); l++) {
cout << *l << " ";
}
cout << endl;
}
}
Kam-Hung Sohhttp://softwaresalariman.blogspot.com
Advertisement
i may be wrong, but it looks like this will only handle one value per key. i want to be able to create a dynamic linked list for every node(key). i'm going to go research maps a little more though. cheers.
nevermind, i was wrong. i still don't know if using map is the best solution for me though, because i don't want the list to be sorted. thanks for the idea though.
Why don't you use std::multimap instead, its guaranteed to always be sorted and there is no limit on the number of elements with the same key so i would just have a multimap of string to strings meaning:

std::multimap< std::string, std::string > mm;


here is an example of using multimap and what i mean:

#include <string>#include <map>#include <iostream>int main() {  typedef std::multimap<std::string, int> mm;  mm m;    m.insert(std::make_pair("a", 1));  m.insert(std::make_pair("c", 2));  m.insert(std::make_pair("b", 3));  m.insert(std::make_pair("b", 4));  m.insert(std::make_pair("a", 5));  m.insert(std::make_pair("b", 6));  std::cout << "Number of elements with key a: " << m.count("a") << '\n';  std::cout << "Number of elements with key b: " << m.count("b") << '\n';  std::cout << "Number of elements with key c: " << m.count("c") << '\n';  std::cout << "Elements in m: " << '\n';  for(mm::iterator itr = m.begin();      itr != m.end();       ++itr)     std::cout << "  [" << (*itr).first << ", " << (*itr).second << "]" << '\n';}

This topic is closed to new replies.

Advertisement