c++ - Printing an array of STL list -


i'm having trouble printing array of lists (ex. list<string> hashtable[100] )

heres have far, question @ bottom:

hash2.h

1 #ifndef __hash2_h 2 #define __hash2_h 3 4 #include<string> 5 #include<list> 6 #include<fstream> 7 8 using namespace std; 9 10 class hash 11 { 12  public: 13    void processfile(string filename); 14    void print(); 15 16  private: 17   list<string> hashtable[100]; 18 19  private: 20   int hf(string ins); 21 22 23 }; 24 25 #endif 

hash_function2.cpp

 1 #include<iostream>  2 #include<string>  3 #include<fstream>  4 #include "hash2.h"  5  6 using namespace std;  7  8 void hash::processfile(string filename)  9 {  10  string word;  11  ifstream myifile(filename.c_str());  12  while(getline(myifile, word))  13  {  14   int index = hf(word);  15   hashtable[index].push_back(word);  16  }  17  myifile.close();  18 }  19  20 void hash::print()  21 {  22  for(int = 0; < 100; i++)  23  {  24   if(hashtable[i] != null)  25   {  26    list<int>::iterator i;  27    for(i = hashtable[i].begin(); != hashtable[i].end(); ++i)  28    {  29     cout << *i << endl;  30    }  31   }  32  }  33 }  34  35 int hash::hf(string ins)  36 {  37  return ( (int) ins[0] ) % 100;  38 } 

main2.cpp

  1 #include "hash2.h"   2 #include<iostream>   3 #include<iomanip>   4 #include<fstream>   5   6 using namespace std;   7   8 int main()   9 {   10  hash hashtable;   11  hashtable.processfile("test1.txt");   12  hashtable.print();   13 } 

so, have processfile function, takes text file, reads each word in, performs hash function(crappy, know), puts word in array index hash function returned. working fine think.

what im having issues using stl list. so, in hash_function2.cpp, want print hash table. i'm not sure how check if array index empty(doesn't have of words stored), , not sure how print strings in list @ given array index. print hash table; print() function working.

if point me in right direction awesome! appreciated.

you shouldn't checking null because have array of std::list objects, not pointers.

you can check if list @ index i has elements with:

if (!hashtable[i].empty()) {     // there elements in list } 

or

if (hashtable[i].size()) {     // there elements in list } 

also in print() function, you're using iterator of type std::list<int>, should std::list<string>, matches declaration of hashtable.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -