当我在c++中使用vector类时会发生什么?
What happens when I use vector with classes in c++
我有一个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.
}
相关文章:
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 向后迭代 std::array 或 std::vector 的正确方法是什么?
- 这句话是什么意思 - " vector<long long> distance(n, std::numeric_limits<long long>::max()); "?
- 最接近"std::atomic<std::vector>"是什么?
- 行 - " vector<int> used(adj.size(), 0); "是什么意思?
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 代码中的"vector<<int>vector>&index"是什么意思?
- 释放 std::vector 中指针内存的最有效方法是什么?
- 当我们push_back元素时,std::vector 什么时候会放大自己?
- 如果我将"reference to vector"分配给"vector"会发生什么情况
- vector.back()和vector.end()有什么区别
- 这个(const vector<vector<int> > &A)"代码段是什么意思?
- 什么是vector<int,int>它甚至有效吗?
- std::shared_ptr<std::vector有什么问题<double>>
- 带有 std::vector 和 std::queue 的 Prim's 算法,我的代码有什么问题?
- std::vector<int> 和 std::vector* 有什么区别<int>?