返回对矢量元素的引用

Returning a reference to vector element

本文关键字:引用 元素 返回      更新时间:2023-10-16
#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
}
无法将"员工">

转换为"员工*"作为回报 返回 content.at(i(;

我在函数"模板中返回对矢量元素的引用时遇到问题 T* map_template::查找(键("。我也无法更改主要功能。如果sb能帮助我,我会很棒。我是 c++ 的新手,所以请理解。 ^

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

将其更改为:

return &content.at(i);

以返回指向元素的指针。

并且,在末尾添加一个return nullptr;,以便在到达函数末尾时摆脱UB。