二维向量与一维向量 [英] 2D vector vs 1D vector

查看:116
本文介绍了二维向量与一维向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++11 中,二维向量与一维向量在时间上的关系如何?
在给定的二维向量中,所有内部向量的大小相同.

In C++11, how does a 2D vector against 1D vector in terms of time?
In the 2D vector given, all the inner vectors are of the same size.

例如:

std::vector<std::vector<int>> X{10, std::vector<int>(4)};

对比

std::vector<int> Y(40);

当随机访问元素时,向量的哪个化身会表现得更好?

Which avatar of the vector would perform better when the elements are randomly accessed?

推荐答案

单个 std::vector 本质上更简单,它只是存储在某处的连续内存块.

A single std::vector is inherently simpler, it's just a contiguous block of memory stored somewhere.

std::vectorstd::vector 有更多的开销,但它也更强大(例如,因为每个内部向量可以有不同的大小).

A std::vector of std::vector has more overhead but it's also more powerful (since each inner vector can be of different size, for example).

应该针对您的特定使用模式对随机访问性能进行彻底的基准测试,但主要区别在于:

Random access performance should be benchmarked thoroughly for your specific pattern of usage but the main difference is that:

  • 使用单个向量,您只需计算 size_t index = x + y*WIDTH 并访问元素
  • 对于嵌套向量,你有两级间接,首先你必须获得包含内部向量的内存,然后你必须获得内部向量数据的内存.

这篇关于二维向量与一维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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