首页 > 解决方案 > 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; 
}

标签: c++

解决方案


userlist函数的第四个参数adduser()是按值调用,将其更改为按引用调用。并对功能做同样的事情delete()


推荐阅读