2013-10-14 26 views
0

我无法输出我列出的矢量的矢量:1.4.3 C++中列出

class index_table { 

public: 
    index_table() { table.resize(128);} 
    void insert(string &, int); 

private: 
    class entry 
    { 
     public: 
     string word; 
     vector <int> line; 
    }; 

    vector< list <entry> > table; 
}; 

我知道了,这样它会填满:

int main() 
{ 
index_table table; 
string word, 
int num = 5; //this is going to a random number. 5 is a temp. place holder. 

while (cin >> word) 
    table.insert(word, num); 

} 

但如何输出它?我尝试了很多不同的方法,但是其中很多都给了我错误。
我是否必须超载操作员?我不完全确定我将如何做到这一点。

回答

3

假设你真的有一个很好的理由使用std::vector< std::list<entry> >,然后根据给定结构,词的印刷可能是这样的:

class index_table { 
public: 
    void print() { 
     for (size_t i = 0; i < table.size(); ++i) { 
      std::list<entry>::iterator li; 
      for (li = table[i].begin(); li != table[i].end(); ++li) 
       std::cout << li->word << " "; 
     } 
    } 
    ... 

private: 
    std::vector< std::list<entry> > table; 
    ... 
}; 
1

如果你的编译器支持C++ 11,可以使用两种基于范围的嵌套for循环。查看功能void index_table::dump()

// Output function 
void index_table::dump() { 
    for (list<entry> &le : table) { 
     for (entry &e : le) { 
      e.dump(); 
     } 
    } 
} 

我也是在入门级,其输出两个变量,这是现在私人的内容创建功能dump()

class index_table { 
    public: 
    index_table() { 
     table.resize(128); 
    } 

    void insert (int,string&,int); 
    void dump(); 

    private: 
    class entry { 
     private: 
     string word; 
     int value; 

     public: 
     entry (string word, int value) { 
      this->word = word; 
      this->value = value; 
     } 

     void dump() { 
      cout << "Word/value is: " << word << "/" << value << endl; 
     } 
    }; 

    vector< list <entry> > table; 
}; 

void index_table::insert(int c, string &key, int value) { 
//void index_table::insert(string &key, int value) { 
    entry obj(key, value); 

    table[c].push_back(obj); 
} 

// Output function 
void index_table::dump() { 
    for (list<entry> &le : table) { 
     for (entry &e : le) { 
      e.dump(); 
     } 
    } 
} 

int main (int argc, char **argv) { 
    index_table mytable; 

    string a = "String 0-A"; 
    string b = "String 0-B"; 
    string c = "String 1-A"; 
    string d = "String 1-B"; 
    string e = "String 6-A"; 
    string f = "String 6-B"; 

    mytable.insert(0, a, 1); 
    mytable.insert(0, b, 2); 
    mytable.insert(1, c, 3); 
    mytable.insert(1, d, 4); 
    mytable.insert(6, e, 3); 
    mytable.insert(6, f, 4); 

    mytable.dump(); 
} 

计划的成果:

Word/value is: String 0-A/1 
Word/value is: String 0-B/2 
Word/value is: String 1-A/3 
Word/value is: String 1-B/4 
Word/value is: String 6-A/3 
Word/value is: String 6-B/4 

PS:我也改变了你的代码位,使之成为我的测试运行更加容易。