向量是什么?它们在编程中如何使用? [英] What are vectors and how are they used in programming?

查看:195
本文介绍了向量是什么?它们在编程中如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉向量作为量级和方向的数学/物理概念,但是在编程的背景下,我也不断遇到对向量的引用(例如C ++似乎有stl :: vector库在SO上经常出现).

I'm familiar with the mathematical/physics concept of a vector as a magnitude and a direction, but I also keep coming across references to vectors in the context of programming (for example C++ seems to have a stl::vector library which comes up fairly frequently on SO).

根据上下文,我的直觉是它们是一个非常原始的结构,通常用于表示可变长度数组的线(我想将其大小存储为大小),但这确实会有所帮助如果有人可以为我提供更完整的解释,最好包括在实践中如何以及为什么使用它们.

My intuition from the context has been that they're a fairly primitive construct most often used to represent something along the lines of a variable length array (storing its size as the magnitude, I presume), but it would be really helpful if somebody could provide me with a more complete explanation, preferably including how and why they're used in practice.

推荐答案

来自 http://www.cplusplus.com/reference/stl/vector/

向量容器的实现方式为动态数组;像平常一样数组,向量容器都有元素存储在连续存储中位置,这意味着他们元素不仅可以访问使用迭代器,但也使用偏移量在指向元素的常规指针上.

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

但是与常规数组不同,存储在向量是自动处理的使其得以扩展,并根据需要收缩.

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.

此外,矢量通常可以容纳任何对象-因此您可以创建一个类来保存有关车辆的信息,然后将车队存储在矢量中.

Furthermore, vectors can typically hold any object - so you can make a class to hold information about vehicles, and then store the fleet in a vector.

除了调整大小之外,向量的妙处在于,它们仍然允许在恒定时间内通过索引访问单个元素,就像数组一样.

Nice things about vectors, aside from resizing, is that they still allow access in constant time to individual elements via index, just like an array.

调整大小的权衡是,当您达到当前容量时,它必须重新分配(有时复制到)更多的内存.但是,大多数增加容量的算法每次遇到障碍时都会使容量翻倍,因此,您遇到的日志从未超过log2(可用堆),在整个程序操作的最坏情况下,结果可能是十几倍.

The tradeoff for resizing, is that when you hit the current capacity it has to reallocate, and sometimes copy to, more memory. However most capacity increasing algorithms double the capacity each time you hit the barrier, so you never hit it more than log2(heap available) which turns out to be perhaps a dozen times in the worst case throughout program operation.

-亚当

这篇关于向量是什么?它们在编程中如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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