[英]Initialize vector of structures
Let's I have 我有
struct Vector {
float i,j,k;
}
I want to zero all elements of vec declared below (i,j,k=0) 我想将以下声明的vec的所有元素归零(i,j,k = 0)
std::vector <Vector> vec;
vec.resize(num,0);
I don't want to use reserve() and then push_back() zeroes one by one. 我不想使用reserve()然后push_back()逐个零。 Another thing is, after succesfully initializing vec, I want to set all members of vec to zero again after it is manipulated. 另一件事是,在成功初始化vec之后,我想在操作之后将vec的所有成员再次设置为零。 Is there something like memset for vectors? 有没有类似memset的矢量?
EDIT: I compared all of the methods in Mike Seymour's and Xeo's answers and as a result size_t size = vec.size(); vec.clear(); vec.resize(size);
编辑:我比较了Mike Seymour和Xeo的答案中的所有方法,结果是size_t size = vec.size(); vec.clear(); vec.resize(size);
size_t size = vec.size(); vec.clear(); vec.resize(size);
is the fastest if they are repeated frequently in a loop. 如果它们在循环中频繁重复,则是最快的。
That's very simple: 这很简单:
vec.resize(num);
or initialise it with the required size: 或者用所需的大小初始化它:
std::vector<Vector> vec(num);
Both the constructor and resize
will fill new elements with value-initialised objects. 构造函数和resize
都将使用值初始化对象填充新元素。 A value-initialised object of a type with no default constructor (such as your Vector
) will have all numeric members initialised to zero. 没有默认构造函数(例如Vector
)的类型的值初始化对象将所有数字成员初始化为零。
To reset everything to zero, either 要将所有内容重置为零
size_t size = vec.size();
vec.clear();
vec.resize(size);
or: 要么:
std::fill(vec.begin(), vec.end(), Vector());
or, less efficiently but with a strong exception guarantee: 或者,效率较低但具有强大的例外保证:
std::vector<Vector>(vec.size()).swap(vec);
C++ way of setting all current elements to 0
: 将所有当前元素设置为0
C ++方法:
std::fill( vec.begin(), vec.end(), 0 );
Or, alternatively, to re-initialize to a given size: 或者,或者,重新初始化为给定大小:
vec.clear();
vec.resize(num, 0);
This might not be as performant as memset
, but good enough for 99% of the cases. 这可能不像memset
那样memset
,但足以满足99%的情况。
You can just use memset
, so long your Vector
is a POD type: 您可以使用memset
,只要您的Vector
是POD类型:
std::vector<Vector> v(num, 0); // inital fill
// do stuff
memset(&v[0], 0, sizeof(Vector) * v.size());
Though the C++ version would be with std::fill
虽然C ++版本将使用std::fill
#include <algorithm>
std::fill(v.begin(), v.end(), 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.