c++ - 返回对 vector 元素的引用

标签 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
}

无法将“Employee”转换为“Employee*”作为返回 返回 content.at(i);

我在函数 "template 中返回对 vector 元素的引用时遇到问题 T* map_template::Find(Key key)”。我也不能改变主要功能。如果某人能帮助我,我将不胜感激。我是 c++ 的新手,所以请理解。 ^

最佳答案

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

将其更改为:

return &content.at(i);

返回指向元素的指针。

此外,在末尾添加一个 return nullptr; 以在到达函数末尾时去除 UB。

关于c++ - 返回对 vector 元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860333/

相关文章:

r 沿向量搜索并计算平均值

c++ - 是否可以将批处理的 FFT 与 CUDA 的 cuFFT 库和 cufftPlanMany 重叠?

c++ - 为什么只能在头文件中实现模板?

c++ - 使用 C++ 进行事件驱动的客户端/服务器设计

WPF 绑定(bind)到控件模板上的非依赖属性

c++ - 模板可以决定 C++ 中参数的数量吗?

c++ - 无法正确打印 vector 内容

c++ - 关于 vector 内存存储

c++ - Qt:在子部件上使用 QPainter

c++ - 在 C++11 中检查到期日期