2015-11-22 138 views
0
#include <iostream> 
#include <vector> 

using namespace std; 

class Employee 
{ 
private: 

public: 
    Employee(std::string Name, std::string Position, int Age); 
    std::string Name; 
    int Age; 
    std::string Position; 

}; 

template <class Key, class T> 
class map_template{ 
private: 
    std::vector<Key> keys; 
    std::vector<T> content; 
public: 
    map_template(){} 
    void Add(Key key, T t); 
    T* Find(Key key); 
}; 

Employee::Employee(std::string Name, std::string Position, int Age) 
{ 
    this->Name = Name; 
    this->Position = Position; 
    this->Age = Age; 
} 

template<class Key, class T> 
void map_template <Key, T>::Add(Key key, T t) 
{ 
    keys.push_back(key); 
    content.push_back(t); 
} 

template<class Key, class T> 
T* map_template<Key, T>::Find(Key key) 
{ 
    for(int i = 0; i < keys.size(); i++) 
     if (keys[i] == key) 
     { 
      return content.at(i); 
     } 
} 

int main(void) 
{ 
    typedef unsigned int ID;       //Identification number of Employee 
    map_template<ID,Employee> Database;     //Database of employees 

    Database.Add(761028073,Employee("Jan Kowalski","salesman",28));  //Add first employee: name: Jan Kowalski, position: salseman, age: 28, 
    Database.Add(510212881,Employee("Adam Nowak","storekeeper",54)); //Add second employee: name: Adam Nowak, position: storekeeper, age: 54 
    Database.Add(730505129,Employee("Anna Zaradna","secretary",32)); //Add third employee: name: Anna Zaradna, position: secretary, age: 32 

    //cout << Database << endl;       //Print databese 

    //map_template<ID,Employee> NewDatabase = Database; //Make a copy of database 

    Employee* pE; 
    pE = Database.Find(510212881);     //Find employee using its ID 
    pE->Position = "salesman";       //Modify the position of employee 
    pE = Database.Find(761028073);     //Find employee using its ID 
    pE->Age = 29;          //Modify the age of employee 

    //Database = NewDatabase;        //Update original database 
    enter code here 
    //cout << Database << endl;       //Print original databese 
} 

無法將「員工」轉換爲「員工*」作爲回報 return content.at(i);返回對矢量元素的引用

我有問題返回引用向量元素的函數「模板 T * map_template :: Find(Key key)」。我也不能改變主函數。如果某人能幫助我,我會很感激。我是新來的C++,所以請理解。 ^

+0

編譯器的錯誤信息是什麼?請把你的代碼減少到必要的程度。 – hagello

回答

1

at返回一個引用,而不是指針。

將其更改爲:

return &content.at(i); 

的指針返回的元素。

而且,在末尾添加return nullptr;以在到達函數結束時擺脫UB。

+0

謝謝,你幫了我很多! – Mathew