c++ - C++ Vector不显示包含对象的数据
问题描述
我是 C++ 新手。我搜索了一下,但找不到有用的东西。非常简单的程序,只是试图将“Person”对象存储在 Vector 中并访问这些对象。到目前为止,我的 Vector 包含一个“Person”类型的对象。'Person' 对象有一个 'name' 字段。我只是想显示那个“名称”字段。但是当程序运行时,控制台不会打印任何内容。
我仍然对向量和指针感到满意,所以我的向量设置可能是原因。我的“getName()”函数设置正确。有人可以让我知道我在向量中声明和插入对象的方式以及向量声明/迭代是否正确?
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include "Person.h"
#include "Record.h"
//addition of a user to list
void addUser(int id, int age, std::string name, std::vector<Person*> userList)
{
Person *newPerson = new Person(id, age, name);
userList.push_back(newPerson);
}
//deletion of a user of the list by ID
void deleteUserByID(int id, std::vector<Person*> userList)
{
for(int i = 0; i < userList.size(); i++) {
if (userList.at(i)->getID() == id)
delete userList.at(i);
}
}
//Print all user names in the list
void printUserList(std::vector<Person*> userList)
{
for(auto it = std::begin(v); it != std::end(v); it++)
{
std::string name = it->getName();
}
}
int main ()
{
//create vector
static std::vector<Person*> userList;
//add first user
addUser(626968231, 21, "Ryan", userList);
//print all users (just one so far)
printUserList(userList);
return 0;
}
解决方案
userlist
函数的第四个参数adduser()
是按值调用,将其更改为按引用调用。并对功能做同样的事情delete()
。
推荐阅读
- php - 如何使网站对用户 PHP 不可用?
- vb.net - 无法在 Zebra 打印机上打印表格
- ansible - ansible diff忽略行的顺序
- git - 从本地分支,git push 到另一个远程分支
- javascript - 在文本框上绑定gridview onkeypress
- ios - UIStackView 无法满足的自动布局约束
- node.js - TypeError:无法读取未定义的属性“元素”
- postgresql - 创建一个物化视图,该视图继承进行视图调用的用户的权限
- postgresql - PostgreSQL INSERT INTO 生产表 FROM 暂存表
- php - 如何在 Authorize.net PHP SDK 中设置客户 IP 地址?