c++ std::pair、std::vector 和 std::pair内存复制

发布于 2024-08-16 11:57:55 字数 266 浏览 4 评论 0原文

是否安全

std::vector<std::pair<T1, T2> > myvect

a 第一个元素的内存地址中的 myvect.size()*sizeof(foo) 字节 memcopy 到数组中

struct foo{
    T1 first;
    T2 second;
}

如果为数组分配了与向量大小相同数量的元素,则将

?谢谢

is it safe to memcopy myvect.size()*sizeof(foo) bytes from the memoryadress of the first element of a

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

许你一世情深 2024-08-23 11:57:55

不,包含 T1T2 的类至少不能保证与 std::pair 具有相同的布局或对齐方式在 C++98 中(因为 std::pair 不是 POD 类型)。 C++0x 中的情况可能有所不同。

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). The story may be different in C++0x.

别再吹冷风 2024-08-23 11:57:55

您没有问的问题的答案可能是 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());

std::copy,但给 foo 一个 operator=以一对作为参数。不过,这假设您可以重写 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);

The answer to the question you didn't ask is probably 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. This assumes you can re-write foo, though:

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);
情丝乱 2024-08-23 11:57:55

一般来说,没有。在某些平台/编译器/STL 实现上可能是这样,但无论如何不要这样做。您将依赖于这两个对的实现细节<>和向量<>。

我自己就犯了依赖向量<>的罪过。是一个连续的数组。为此,我深深地忏悔。但这对……就说不吧。

In general, no. On some platforms/compilers/STL implementations it might be, but don't do it anyway. You'd be relying on the implementation details of both pair<> and vector<>.

I myself have committed the sin of relying on vector<> being a contiguous array. For that, I deeply repent. But the pair<>... Just say no.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文