我无法在 C++ 中创建正确的 std::vector

I can't create proper std::vector in c++

我必须创建一个对象列表,因此为了让它尽可能流畅,我想使用 std::vector 而不是常规的对象数组。但是我不完全知道如何正确使用它们。这是我的 class 中的示例代码,我在其中尝试将对象添加到 vecor 并在第二种方法中显示它们。

private:
vector <Student> stud;
public:
void Student::dodaj(){
stud.push_back(Student(getNaz(), getImie(), getLeg(), getRok()));
}

void Student::wypisz(){
cout << "Lista osob:\n";
for (int i = 0; i < 1; i++)
{
    cout << endl;
    cout << "Nazwisko: " << stud[i].nazwisko << endl;
    cout << "Imie: " << stud[i].imie << endl;
    cout << "Numer indeksu.: " << stud[i].legitymacja << endl;
    cout << "Rok studiow: " << stud[i].rok << endl;
}

还有我的主要:

Student st("Kowalski", "Jan", 123455, 2);
Student test1("Nowak", "Jan", 123, 2);
st.dodaj();
test1.dodaj();
test1.wypisz();

然而,输出结果只有一个对象,因为我使用 wypisz(print/display) 方法,在本例中为 test1,而不是显示其中的两个 - st 和 test1。有什么解决方法吗?

看来 studStudent 的成员,这意味着每个 Student 对象都包含自己的向量。当您对特定学生调用 dodaj 时,它只是将自己的详细信息添加到它包含的向量中。

st.dodaj(); // Adds details of st to st's own vector
test1.dodaj(); // Adds details of test1 to test1's own vector

// Now we have one vector inside st containing a single element
// and one vector inside test1 containing a single element    

test1.wypisz(); // Prints elements from test1's vector

相反,您的矢量应该在 Student class 之外(或至少是静态的)。一种选择是这样做:

Student st("Kowalski", "Jan", 123455, 2);
Student test1("Nowak", "Jan", 123, 2);

std::vector<Student> stud;
std.push_back(st);
std.push_back(test1);

您可能想要另一个包含此向量的 class(也许 School?)。