gpt4 book ai didi

c++ - 成对 vector 和包含两个元素的结构 vector 的内存布局差异 - C++/STL

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:21 46 4
gpt4 key购买 nike

test1test2在内存中的布局是否相同?

std::vector<std::pair<int,int> > test1;
std::vector<mystruct> test2;

其中 mystruct 定义为:

struct mystruct{
int a;
int b;
};

最佳答案

如果你在 cplusplus.com 上看到,你会看到这是一对的结构:

template <class T1, class T2> struct pair
{
typedef T1 first_type;
typedef T2 second_type;

T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& x, const T2& y) : first(x), second(y) {}
template <class U, class V>
pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}

完全一样,我会说,除了一些事实:好吧,从 pairs 与 std 容器兼容这一事实开始,例如,映射。此外,这些对已经制成,并且已经有适合您的构造函数。

编辑:我还忘了提及您将拥有 std::make_pair,它允许您跳过分配内存并在结构中创建您自己的对,并且您也定义了一些比较和赋值运算符。

关于c++ - 成对 vector 和包含两个元素的结构 vector 的内存布局差异 - C++/STL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8526484/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com