2015-11-22 2 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 
} 

не может преобразовать 'Employee' в 'Employee *' в свою очередь return content.at (i);Возврат ссылки на элемент вектора

У меня проблема с возвратом ссылки на векторный элемент в функции "template T * map_template :: Find (Key key)". Я не могу изменить основную функцию. Я был бы бод, если бы сб мог мне помочь. Я новичок в C++, поэтому, пожалуйста, поймите. ^

+0

Какое сообщение об ошибке компилятора? Пожалуйста, сократите свой код до необходимого. – hagello

ответ

1

at возвращает ссылку, а не указатель.

Изменить его:

return &content.at(i); 

вернуть указатель на элемент.

А также добавьте return nullptr; в конце, чтобы избавиться от UB, когда достигнете конца функции.

+0

спасибо, ты мне очень помог! – Mathew

Смежные вопросы