2013-10-14 5 views
0

의의 벡터를 출력하기 :내가 문제 목록 내 벡터를 출력하는 데 C의 목록 ++

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); 

} 

하지만 어떻게 : 그것은 채울 수 있도록

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; 
}; 

내가있어 그것을 출력? 나는 여러 가지 접근법을 시도했지만 많은 사람들이 저에게 오류를주고 있습니다.
교환 원에 과부하가 걸립니까? 나는 내가 어떻게 그것을 할 수 있을지 완전히 모른다. 당신이 정말로 std::vector< std::list<entry> >를 사용하는 좋은 이유가 가정

답변

3

가, 지정된 구조를 기반으로, 단어의 인쇄는 다음과 같습니다

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 지원하는 경우, 당신은이를 사용할 수 있습니다 범위 기반 중첩 루프. 기능 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 : 나는 또한 내 테스트에 더 쉽게 실행할 수 있도록 약간의 코드를 변경했습니다.