creating vector of local structure、vector of structs initialization
最后更新于:2022-04-01 06:44:17
##实战c++中的vector系列--creating vector of local structure、vector of structs initialization
之前一直没有使用过`vector<struct>,现在就写一个简短的代码:
`
~~~
#include <vector>
#include <iostream>
int main() {
struct st { int a; };
std::vector<st> v;
v.resize(4);
for (std::vector<st>::size_type i = 0; i < v.size(); i++) {
v.operator[](i).a = i + 1; // v[i].a = i+1;
}
for (int i = 0; i < v.size(); i++)
{
std::cout << v[i].a << std::endl;
}
}
~~~
用VS2015编译成功,运行结果:
1
2
3
4
但是,这是C++11之后才允许的,之前编译器并不允许你写这样的语法,不允许vector容器内放local structure。
更进一步,如果struct里面有好几个字段呢?
~~~
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub;
//Push back new subject created with default constructor.
sub.push_back(subject());
//Vector now has 1 element @ index 0, so modify it.
sub[0].name = "english";
//Add a new element if you want another:
sub.push_back(subject());
//Modify its name and marks.
sub[1].name = "math";
sub[1].marks = 90;
sub.push_back({ "Sport", 70, 0 });
sub.resize(8);
//sub.emplace_back("Sport", 70, 0 );
for (int i = 0; i < sub.size(); i++)
{
std::cout << sub[i].name << std::endl;
}
}
~~~
但是上面的做法不好,我们应该先构造对象,后进行push_back 也许更加明智。
subject subObj;
subObj.name = s1;
sub.push_back(subObj);
这个就牵扯到一个问题,为什么不使用emplace_back来替代push_back呢,这也是我们接下来讨论 话题。