Acess和修改包含具有不同变量类型的对象的C++向量



我刚刚开始学习C++,我想访问和修改具有不同变量类型的对象向量。我只能创建矢量,但对它无能为力。我该如何访问和修改它?这是我迄今为止创建的代码:

class Person {
private: string name; int id;
public: 
Person(string x, int y) { name = x; id = y; };
~Person(); 
};
int main()
{
vector<vector<Person>> v4;
}

要访问存储在矢量中的对象,您有不同的运算符和方法,如at()operator[]。有关更多详细信息,请查看https://www.cplusplus.com/reference/vector/vector/

既然你想学习C++,我想你不知道该问什么,所以让我帮你

除了访问向量中的对象之外,您的代码示例还缺少其他内容:

  • 由于nameid是私有的,您无法访问它们
  • 你的析构函数没有实现
  • 您创建了一个由Persons向量组成的向量。我想你只想要一个向量
  • 关于一个向量中的多个类型的问题:这不容易实现。根据需要,您需要多个向量,或者需要组合数据(例如,通过std::pair,或者需要使用接口和继承
  • 您的矢量为空

让我构建一些东西,给你一个关于在哪里继续的提示:

#include <iostream>
#include <string>
#include <vector>
class Person {
private: 
std::string name;
int id;
public: 
Person(std::string x, int y) { name = x; id = y; };
// ~Person();  //This is not needed, since your class currently does not need any special handling during destruction
// You need to be able to access name and id to be able to do something with them, for example print it
std::string getName() const { 
// be aware that this creates a copy of name. Thus changes to the returned string will not be reflected in the Person object.
// Another option would be returning a reference (std::string&), but that I leave for you to research yourself
return name;
} 
int getId() const {
// same as for the name applies
return id;
}
// This allows us to change the id of a Person
void setId(int newId) {
id = newId;
} 
};
int main()
{
// Lets create a Person first:
Person p ("John", 1); // Please note that the string literal here will be used to construct an std::string on the fly and then store it in name of p
// Create a second Person:
Person p2 ("Jim", 2);
// Create a vector and add the persons to it
std::vector<Person> v;
v.push_back(p);
v.push_back(p2);
// Print out the contents of the vector
for (auto& pers : v) {
std::cout << "Person " << pers.getName() << " has id " << pers.getId() << std::endl;
}
// Now change the id of the second person in the vector to 5 (note that indexes start at 0)
v.at(1).setId(5);
// Print again
for (auto& pers : v) {
std::cout << "Person " << pers.getName() << " has id " << pers.getId() << std::endl;
}
}

要玩它:https://godbolt.org/z/8dfEoa

我希望这能帮助你开始。

最新更新