返回对vector元素的引用

时间:2015-11-22 21:19:31

标签: c++ templates vector reference

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

我在函数“模板中返回对vector元素的引用时遇到了问题     T * map_template :: Find(Key key)“。我也无法改变主要功能。如果某人能帮助我,我会很高兴。我是c ++的新手,所以请理解。                                 ^

1 个答案:

答案 0 :(得分:1)

at返回引用,而不是指针。

将其更改为:

return &content.at(i);

返回指向元素的指针。

此外,最后添加return nullptr;以在到达函数末尾时摆脱UB。