[英]c++ std::pair, std::vector & memcopy
is it safe to memcopy myvect.size()*sizeof(foo) bytes from the memoryadress of the first element of a 从第一个元素的memoryadress中记忆myvect.size()* sizeof(foo)字节是否安全?
std::vector<std::pair<T1, T2> > myvect
into an array of 成阵列
struct foo{
T1 first;
T2 second;
}
if the array is allocated with the same number of elements as the vector's size? 如果为数组分配的元素数与向量的大小相同?
thanks 谢谢
No, a class containing T1
and T2
is not guaranteed the same layout or alignment as std::pair<T1, T2>
, at least in C++98 (since std::pair
is not a POD type). 不,包含
T1
和T2
的类不能保证与std::pair<T1, T2>
相同的布局或对齐,至少在C ++ 98中(因为std::pair
不是POD类型)。 The story may be different in C++0x. C ++ 0x中的故事可能有所不同。
The answer to the question you didn't ask is probably std::transform
: 你没问过的问题的答案可能是
std::transform
:
struct pairToFoo {
// optionally this can be a function template.
// template<typename T1, typename T2>
foo operator()(const std::pair<T1,T2> &p) const {
foo f = {p.first, p.second};
return f;
}
};
std::transform(myvect.begin(), myvect.end(), myarray, pairToFoo());
Or std::copy
, but give foo an operator=
taking a pair as parameter. 或
std::copy
,但给foo一个operator=
取一对作为参数。 This assumes you can re-write foo, though: 这假设你可以重写foo,但是:
struct foo {
T1 first;
T2 second;
foo &operator=(const std::pair<T1,T2> &p) {
first = p.first;
second = p.second;
return *this;
}
};
std::copy(myvect.begin(), myvect.end(), myarray);
In general, no. 一般来说,没有。 On some platforms/compilers/STL implementations it might be, but don't do it anyway.
在某些平台/编译器/ STL实现上它可能是,但不管怎么说都不这样做。 You'd be relying on the implementation details of both pair<> and vector<>.
你将依赖于对<>和vector <>的实现细节。
I myself have committed the sin of relying on vector<> being a contiguous array. 我自己犯了依赖vector <>成为连续数组的罪。 For that, I deeply repent.
为此,我深深地忏悔。 But the pair<>... Just say no.
但是这对<> ......说不。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.