std :: pair< int,int> vs struct with two int's [英] std::pair<int, int> vs struct with two int's

查看:146
本文介绍了std :: pair< int,int> vs struct with two int's的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ACM示例中,我不得不为动态编程构建一个大表。我必须在每个单元格中存储两个整数,所以我决定去一个 std :: pair< int,int> 。然而,分配一个庞大的数组需要1.5秒:

In an ACM example, I had to build a big table for dynamic programming. I had to store two integers in each cell, so I decided to go for a std::pair<int, int>. However, allocating a huge array of them took 1.5 seconds:

std::pair<int, int> table[1001][1001];

之后,我将此代码更改为

Afterwards, I have changed this code to

struct Cell {
    int first;
    int second;
}

Cell table[1001][1001];

,分配耗时0秒。

推荐答案

std :: pair< int,int> ;: :pair()构造函数使用默认值(在 int 的情况下为零)和 struct Cell 不会(因为你只有一个自动生成的默认构造函数不起作用)。

std::pair<int, int>::pair() constructor initializes the fields with default values (zero in case of int) and your struct Cell doesn't (since you only have an auto-generated default constructor that does nothing).

初始化需要写入每个字段,的相对耗时的存储器访问。使用 struct Cell 没有做任何事情,不做任何事情有点快。

Initializing requires writing to each field which requires a whole lot of memory accesses that are relatively time consuming. With struct Cell nothing is done instead and doing nothing is a bit faster.

这篇关于std :: pair&lt; int,int&gt; vs struct with two int's的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆