gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:57:27 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com