当我在c++中使用vector类时会发生什么?

What happens when I use vector with classes in c++

本文关键字:什么 vector c++      更新时间:2023-10-16

我有一个Person类并创建一个Person类型向量。我想知道,当我调用一个Person类型的函数,索引是向量的时候会发生什么。这是在数组中存储对象还是什么?请提前简单解释一下,谢谢。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Person
{
int age;
string name;
public:
Person(){};
void getdata()
{
    cout << "Enter your name: ";
    getline(cin >> ws, name);
    cout << "Enter your age: ";
    cin >> age;
}
void showdata()
{
    cout << "nHello " << name << " your age is " << age;
}
};
void main()
{
vector<Person> myVector(3); 
unsigned int i = 0;
for (i; i < 3; i++)
    myVector[i].getdata();//Does this create & save an objects in that  location   Please explain briefly, Thanks
for (i=0; i < 3; i++)       //What if I do this like
                            /*for (i=0; i < 3; i++)
                                { Person p;
                                myVector.puskback(p); }
                                or what if I want a new data then what??*/
    myVector[i].showdata();
system("pause");
}

不,它不创建对象。当你的矢量被创建时,所有的对象都被创建了。它所做的是,在已经构造的对象上调用getdata()。您可以按照您建议的方式进行推退,在这种情况下,您希望最初创建一个空向量(现在您正在创建一个具有3个元素的向量)

考虑

class A
{
public:
    A(){}
    foo(){}
};
...
int main()
{
     std::vector<A> v1(3);
     //this creates a vector with 3 As by calling the empty constructor on each
     //means means you can readily manipulate these 3 As in v1
     for(int i = 0; i < v1.size(); i++)
         v1[i].foo();
     std::vector<A> v2;
     //this creates a vector of As with no pre-instantiated As
     //you have to create As to add to the vector
     A a1;
     v2.push_back(a1);
     //you can now manipulate a1 in v2
     v2[0].foo(); 
     //You can add to v1 after having initially created it with 3 As
     A a2;
     v1.push_back(a2);
     //You have all the flexibility you need.
}
相关文章: