胃烂了是什么病严重吗| 为什么尿黄| 蟑螂幼虫长什么样| 下午5点半是什么时辰| 手腕长痣代表什么意思| 喝什么茶对肾好| 大脑精神紊乱什么病| 胎位左枕前是什么意思| 牙龈肿痛吃什么药好| 尿糖1十是什么意思| 什么可以代替润滑油| 怀孕周期是从什么时候开始算的| 一去不返是什么生肖| 网络是什么意思| 4月25日是什么星座| 女人阴部黑是什么原因| 老人流口水是什么原因| 高铁座位为什么没有e| 肾主骨是什么意思| 维生素b2起什么作用| 蜻蜓是什么动物| 赑屃是什么意思| 发烧适合吃什么食物| 花苞裤不适合什么人穿| 头皮发痒是什么原因引起的| 什么叫梅核气| 维生素d和维生素ad有什么区别| 回南天什么意思| 为什么打嗝| 笑什么| 小米粥和什么搭配最好最养胃| 巴宝莉是什么牌子| 子宫息肉有什么危害| 你在做什么| 天下乌鸦一般黑是什么意思| 脸油油的是什么原因| 女人吃牛蛙有什么好处| 孕妇适合吃什么水果| 蒙字五行属什么| 子宫切除后要注意什么| 男人左眼跳是什么预兆| 什么叫一个周期| 刷酸是什么| nt检查什么内容| 做梦来月经了什么预兆| 斐乐是什么档次| 高危hpv阳性是什么意思| 用膳是什么意思| 梦见粉条是什么意思| 三教九流代表什么生肖| 小腿经常抽筋是什么原因| 大白菜什么时候种| 什么是还原糖| 为什么近视不可逆| 脉弱是什么意思| 吃中药为什么要忌口| 什么是沙龙| 贝前列素钠片主治什么病| 夏枯草有什么作用| bhpc是什么牌子| 女生下面长什么样| 猫什么时候打疫苗| 排骨粥要搭配什么好吃| peg是什么意思| 多吃火龙果有什么好处和坏处| 早晨起床口干口苦是什么原因| 吃什么减脂肪最快最有效的方法| 牛皮癣用什么药膏最好| 哈喇子是什么意思| 送情人什么礼物最好| 巴洛特利为什么叫巴神| hcv是什么意思| 双胞胎代表什么生肖| 黄芪和什么搭配最好| 风风火火是什么生肖| 10pcs是什么意思| 早上打碎碗是什么兆头| esmara是什么品牌| 万宝龙手表什么档次| 腹泻可以吃什么| experiment是什么意思| 什么家门| 武汉市长是什么级别| 亚硝酸盐阴性是什么意思| 骨折是什么意思| 慈禧为什么要毒死光绪| 刻薄什么意思| sheet是什么意思| 目前是什么意思| 什么是心率| 宝宝照蓝光有什么副作用| 多彩的什么| 怀孕第一个月最怕什么| 心衰用什么药| 眼睛干涩是什么原因| 企鹅是什么动物| 什么水果利尿效果最好| 六盘水为什么叫凉都| 盐酸安罗替尼胶囊主要治疗什么| 还记得年少时的梦吗是什么歌| 晒伤擦什么药| 车前草有什么功效| 胎盘血池是什么意思| 乔丹是什么牌子| 梦见自己家被盗有什么预兆| 皮肤黄是什么原因| 阿莫西林不能和什么药一起吃| 猴子怕什么| 更年期吃什么药| 剁椒鱼头属于什么菜系| 蜱虫最怕什么药| 女人小腹痛什么原因| 为什么学习不好| 改良是什么意思| 车前草长什么样| 乐五行属性是什么| 六块钱麻辣烫什么意思| 什么情况需要做胃镜| 高大上是什么意思| 晚餐吃什么减肥| 糖类抗原125是什么指标| 什么是白茶| 女生胸部什么时候停止发育| 做肠胃镜挂什么科| 蚊子的天敌是什么| 什么是相位| 口臭是什么原因| 三心二意是什么意思| 宗师是什么意思| 湿疹是什么皮肤病| 狗不能吃什么东西| 去湿气吃什么食物好| 猎头是干什么的| 28岁今年属什么| 什么是缘分| 什么原因导致卵巢早衰| 健身吃蛋白粉有什么好处和坏处| 浮萍是什么意思| 磁场是什么| 前方高能什么意思| 肾不好会有什么症状| 男孩子送什么礼物| 成本倒挂什么意思| 奄奄一息的息是什么意思| 人次什么意思| 缺蛋白质吃什么补得快| 梦到喝酒是什么意思| 口腔溃疡吃什么菜| 缺铁性贫血吃什么| 防蓝光是什么意思| 属相鸡与什么属相相合| 射手座喜欢什么样的女生| 凤毛麟角是什么生肖| 右肋骨下方是什么器官| 小狗能吃什么水果| 为什么吃一点东西肚子就胀| 8月21日是什么星座| 梨子什么时候成熟| 睡美人最怕得什么病| 大便绿色什么原因| 夹生是什么意思| 奇异是什么意思| 私处瘙痒用什么药| 雾化对小孩有什么影响或者副作用| 放荡不羁爱自由什么意思| 女人抖腿代表什么意思| 什么是苔藓皮肤病| 牛皮革是什么意思| ua是什么单位| 感冒喉咙痒吃什么药| 松鼠咬人后为什么会死| 塑料袋属于什么垃圾| 灵芝有什么作用| 身体有异味是什么原因| hdr是什么拍照功能| 沙眼用什么眼药水| 红润润的什么| 235是什么意思| adhd是什么病| 经常手麻是什么原因引起的| 脚浮肿是什么原因| 什么血型是万能血型| 喝酒前吃什么不会醉| 眼睛有点模糊是什么原因| 阑尾是什么器官| 怀孕初期会有什么症状| mirror什么意思| soie是什么面料| 宝宝吃益生菌有什么好处和坏处| 做肝功能检查挂什么科| 促甲状腺激素高是什么原因| 碳水化合物对人体有什么作用| 风寒吃什么感冒药| 为什么舌头老是有灼烧感| 死海为什么叫死海| 为什么一来月经就头疼| 腺瘤样增生是什么意思| 吃什么补充蛋白| 辅酶q10什么时间吃最好| 梦到自己结婚什么意思| 假牛肉干是什么做的| 东方是什么意思| ab和b型血生的孩子是什么血型| 什么酷暑| 早上四五点是什么时辰| seiko手表是什么牌子| 阿斯伯格综合症是什么| 赵本山是什么学历| 凝神是什么意思| 小白脸是什么意思| 运动不出汗是什么原因| 秋葵有什么营养| 什么是凌汛| 白细胞酯酶阳性是什么意思| 馨字取名有什么寓意| 调制乳粉是什么意思| 什么叫高危性行为| 618是什么星座| 生蒜头吃了有什么好处和坏处| 圣母娘娘是什么神| 胃食管反流咳嗽吃什么药| 什么是滑精| 被口是什么感觉| 人死后为什么要盖住脸| 日月星辰下一句是什么| 世俗是什么意思| 胆固醇高不能吃什么食物| 台甫是什么意思| 压力大会有什么症状| 什么洗发水好| 2034年是什么年| 怀孕甲减对孩子有什么影响| 很无奈是什么意思| 筛窦炎是什么病| 615是什么星座| 海燕是什么鸟| 欣什么若什么| sin是什么边比什么边| 机关党委是干什么的| 凌晨两点是什么时辰| zgo手表是什么牌子| 鼻咽癌是什么| 唾液酸苷酶阳性什么意思| 跑步后尿血是什么情况| 云南在古代叫什么| 人死之前为什么会拉屎| 罗贯中是什么朝代的| 落枕吃什么药好得快| 表姐的女儿叫什么| 月经来了腰疼是什么原因| 2003年属羊是什么命| 为什么德牧不能打| 秋刀鱼是什么鱼| 人中上窄下宽代表什么| 盆腔炎是什么症状| 痛风看什么科| 缺钙吃什么补得最快| 嗓子有点疼吃什么药| 麻雀吃什么| 藿香正气水什么时候喝| 1991年是什么命| 脸颊两边长痘痘是什么原因引起的| 前列腺炎有什么症状| 喝酒后头疼是什么原因| 百度Jump to content

·一周中医减肥食谱介绍 善用枸杞消除身体水肿

From Wikipedia, the free encyclopedia
(Redirected from Std::vector)
百度 推动经济高质量发展,要把重点放在推动产业结构转型升级上,把实体经济做实做强做优。

In computing, sequence containers refer to a group of container class templates in the standard library of the C++ programming language that implement storage of data elements. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. One common property of all sequential containers is that the elements can be accessed sequentially. Like all other standard library components, they reside in namespace std.

The following containers are defined in the current revision of the C++ standard: array, vector, list, forward_list, deque. Each of these containers implements different algorithms for data storage, which means that they have different speed guarantees for different operations:[1]

Since each of the containers needs to be able to copy its elements in order to function properly, the type of the elements must fulfill CopyConstructible and Assignable requirements.[2] For a given container, all elements must belong to the same type. For instance, one cannot store data in the form of both char and int within the same container instance.

History

[edit]

Originally, only vector, list and deque were defined. Until the standardization of the C++ language in 1998, they were part of the Standard Template Library (STL), published by SGI. Alexander Stepanov, the primary designer of the STL, bemoans the choice of the name vector, saying that it comes from the older programming languages Scheme and Lisp but is inconsistent with the mathematical meaning of the term.[3]

The array container at first appeared in several books under various names. Later it was incorporated into a Boost library, and was proposed for inclusion in the standard C++ library. The motivation for inclusion of array was that it solves two problems of the C-style array: the lack of an STL-like interface, and an inability to be copied like any other object. It firstly appeared in C++ TR1 and later was incorporated into C++11.

The forward_list container was added to C++11 as a space-efficient alternative to list when reverse iteration is not needed.

Properties

[edit]

array, vector and deque all support fast random access to the elements. list supports bidirectional iteration, whereas forward_list supports only unidirectional iteration.

array does not support element insertion or removal. vector supports fast element insertion or removal at the end. Any insertion or removal of an element not at the end of the vector needs elements between the insertion position and the end of the vector to be copied. The iterators to the affected elements are thus invalidated. In fact, any insertion can potentially invalidate all iterators. Also, if the allocated storage in the vector is too small to insert elements, a new array is allocated, all elements are copied or moved to the new array, and the old array is freed. deque, list and forward_list all support fast insertion or removal of elements anywhere in the container. list and forward_list preserves validity of iterators on such operation, whereas deque invalidates all of them.

Vector

[edit]

The elements of a vector are stored contiguously.[4] Like all dynamic array implementations, vectors have low memory usage and good locality of reference and data cache utilization. Unlike other STL containers, such as deques and lists, vectors allow the user to denote an initial capacity for the container.

Vectors allow random access; that is, an element of a vector may be referenced in the same manner as elements of arrays (by array indices). Linked-lists and sets, on the other hand, do not support random access or pointer arithmetic.

The vector data structure is able to quickly and easily allocate the necessary memory needed for specific data storage, and it is able to do so in amortized constant time. This is particularly useful for storing data in lists whose length may not be known prior to setting up the list but where removal (other than, perhaps, at the end) is rare. Erasing elements from a vector or even clearing the vector entirely does not necessarily free any of the memory associated with that element.

Capacity and reallocation

[edit]

A typical vector implementation consists, internally, of a pointer to a dynamically allocated array,[1] and possibly data members holding the capacity and size of the vector. The size of the vector refers to the actual number of elements, while the capacity refers to the size of the internal array.

When new elements are inserted, if the new size of the vector becomes larger than its capacity, reallocation occurs.[1][5] This typically causes the vector to allocate a new region of storage, move the previously held elements to the new region of storage, and free the old region.

Because the addresses of the elements change during this process, any references or iterators to elements in the vector become invalidated.[6] Using an invalidated reference causes undefined behaviour.

The reserve() operation may be used to prevent unnecessary reallocations. After a call to reserve(n), the vector's capacity is guaranteed to be at least n.[7]

The vector maintains a certain order of its elements, so that when a new element is inserted at the beginning or in the middle of the vector, subsequent elements are moved backwards in terms of their assignment operator or copy constructor. Consequently, references and iterators to elements after the insertion point become invalidated.[8]

C++ vectors do not support in-place reallocation of memory, by design; i.e., upon reallocation of a vector, the memory it held will always be copied to a new block of memory using its elements' copy constructor, and then released. This is inefficient for cases where the vector holds plain old data and additional contiguous space beyond the held block of memory is available for allocation.

Specialization for bool

[edit]

The Standard Library defines a specialization of the vector template for bool. The description of this specialization indicates that the implementation should pack the elements so that every bool only uses one bit of memory.[9] This is widely considered a mistake.[10][11] vector<bool> does not meet the requirements for a C++ Standard Library container. For instance, a container<T>::reference must be a true lvalue of type T. This is not the case with vector<bool>::reference, which is a proxy class convertible to bool.[12] Similarly, the vector<bool>::iterator does not yield a bool& when dereferenced. There is a general consensus among the C++ Standard Committee and the Library Working Group that vector<bool> should be deprecated and subsequently removed from the standard library, while the functionality will be reintroduced under a different name.[13]

List

[edit]

The list data structure implements a doubly linked list. Data is stored non-contiguously in memory which allows the list data structure to avoid the reallocation of memory that can be necessary with vectors when new elements are inserted into the list.

The list data structure allocates and deallocates memory as needed; therefore, it does not allocate memory that it is not currently using. Memory is freed when an element is removed from the list.

Lists are efficient when inserting new elements in the list; this is an ?? operation. No shifting is required like with vectors.

Lists do not have random-access ability like vectors (?? operation). Accessing a node in a list is an ?? operation that requires a list traversal to find the node that needs to be accessed.

With small data types (such as ints) the memory overhead is much more significant than that of a vector. Each node takes up sizeof(type) + 2 * sizeof(type*). Pointers are typically one word (usually four bytes under 32-bit operating systems), which means that a list of four byte integers takes up approximately three times as much memory as a vector of integers.

Forward list

[edit]

The forward_list data structure implements a singly linked list.

Deque

[edit]

deque is a container class template that implements a double-ended queue. It provides similar computational complexity to vector for most operations, with the notable exception that it provides amortized constant-time insertion and removal from both ends of the element sequence. Unlike vector, deque uses discontiguous blocks of memory, and provides no means to control the capacity of the container and the moment of reallocation of memory. Like vector, deque offers support for random-access iterators, and insertion and removal of elements invalidates all iterators to the deque.

Array

[edit]

array implements a non-resizable array. The size is determined at compile-time by a template parameter. By design, the container does not support allocators because it's basically a C-style array wrapper.

Overview of functions

[edit]

The containers are defined in headers named after the names of the containers, e.g. vector is defined in header <vector>. All containers satisfy the requirements of the Container concept, which means they have begin(), end(), size(), max_size(), empty(), and swap() methods.

Member functions

[edit]
Functions array
(C++11)
vector
deque
list
forward_list
(C++11)
Description
Basics (implicit) (constructor) (constructor) (constructor) (constructor) Constructs the container from variety of sources
(destructor) (destructor) (destructor) (destructor) Destructs the container and the contained elements
operator= operator= operator= operator= Assigns values to the container
assign assign assign assign Assigns values to the container
Allocators get_allocator get_allocator get_allocator get_allocator Returns the allocator used to allocate memory for the elements
Element
access
at at at Accesses specified element with bounds checking.
operator[] operator[] operator[] Accesses specified element without bounds checking.
front front front front front Accesses the first element
back back back back Accesses the last element
data data Accesses the underlying array
Iterators begin
cbegin
begin
cbegin
begin
cbegin
begin
cbegin
begin
cbegin
Returns an iterator to the beginning of the container
end
cend
end
cend
end
cend
end
cend
end
cend
Returns an iterator to the end of the container
rbegin
crbegin
rbegin
crbegin
rbegin
crbegin
rbegin
crbegin
Returns a reverse iterator to the reverse beginning of the container
rend
crend
rend
crend
rend
crend
rend
crend
Returns a reverse iterator to the reverse end of the container
Capacity empty empty empty empty empty Checks whether the container is empty
size size size size Returns the number of elements in the container.
max_size max_size max_size max_size max_size Returns the maximum possible number of elements in the container.
reserve Reserves storage in the container
capacity Returns the number of elements that can be held in currently allocated storage
shrink_to_fit shrink_to_fit Reduces memory usage by freeing unused memory (C++11)
Modifiers clear clear clear clear Clears the contents
insert insert insert Inserts elements
emplace emplace emplace Constructs elements in-place (C++11)
erase erase erase Erases elements
push_front push_front push_front Inserts elements to the beginning
emplace_front emplace_front emplace_front Constructs elements in-place at the beginning (C++11)
pop_front pop_front pop_front Removes the first element
push_back push_back push_back Inserts elements to the end
emplace_back emplace_back emplace_back Constructs elements in-place at the end (C++11)
pop_back pop_back pop_back Removes the last element
insert_after Inserts elements after specified position (C++11)
emplace_after Constructs elements in-place after specified position (C++11)
erase_after Erases elements in-place after specified position (C++11)
resize resize resize resize Changes the number of stored elements
swap swap swap swap swap Swaps the contents with another container of the same type
fill Fills the array with the given value

There are other operations that are available as a part of the list class and there are algorithms that are part of the C++ STL (Algorithm (C++)) that can be used with the list and forward_list class:

Operations

[edit]

Non-member functions

[edit]

Usage example

[edit]

The following example demonstrates various techniques involving a vector and C++ Standard Library algorithms, notably shuffling, sorting, finding the largest element, and erasing from a vector using the erase-remove idiom.

#include <iostream>
#include <vector>
#include <array>
#include <algorithm> // sort, max_element, random_shuffle, remove_if, lower_bound 
#include <functional> // greater
#include <iterator> // begin, end, cbegin, cend, distance
#include <random> // per std::shuffle
/*
Explanation of Corrections (Giorgio Ruffa 02-23-2025):

    Shuffle Error: The std::shuffle function requires a third argument that provides a random number generator. I added a random number generator based on std::random_device and std::mt19937.

    Character Error: The quotes used around '\n' were non-standard characters (common in text editors or document formatting). I replaced them with the standard quotes for C++.

    Lambda and erase Error: The closure of the call to remove_if was incorrect; a second argument must be provided to erase, which is the end iterator. I added end(numbers).
*/
using namespace std;

int main()
{
    array arr{ 1, 2, 3, 4 };

    // initialize a vector from an array
    vector<int> numbers(cbegin(arr), cend(arr));

    // insert more numbers into the vector
    numbers.push_back(5);
    numbers.push_back(6);
    numbers.push_back(7);
    numbers.push_back(8);
    // the vector currently holds { 1, 2, 3, 4, 5, 6, 7, 8 }

    // randomly shuffle the elements
    random_device rd; // Seed for the random number generator
    mt19937 g(rd()); // Mersenne Twister random number engine
    shuffle(begin(numbers), end(numbers), g); // Aggiunto il generatore come terzo argomento

    // locate the largest element, O(n)
    auto largest = max_element(cbegin(numbers), cend(numbers));

    cout << "The largest number is " << *largest << "\n";
    cout << "It is located at index " << distance(largest, cbegin(numbers)) << "\n";

    // sort the elements
    sort(begin(numbers), end(numbers));

    // find the position of the number 5 in the vector 
    auto five = lower_bound(cbegin(numbers), cend(numbers), 5);

    // Corretto l'uso delle virgolette
    cout << "The number 5 is located at index " << distance(five, cbegin(numbers)) << '\n';

    // erase all the elements greater than 4   
    numbers.erase(
        remove_if(begin(numbers),
                   end(numbers),
                   [](auto n) constexpr { return n > 4; }), // Aggiunto il ';' corretto qui
        end(numbers)); // Aggiunto end(numbers) come secondo argomento per 'erase'

    // print all the remaining numbers
    for (const auto& element : numbers)
        cout << element << " ";
}

The output will be the following:

The largest number is 8
It is located at index 6 (implementation-dependent)
The number 5 is located at index 4
1 2 3 4

References

[edit]
  • William Ford, William Topp. Data Structures with C++ and STL, Second Edition. Prentice Hall, 2002. ISBN 0-13-085850-1. Chapter 4: The Vector Class, pp. 195–203.
  • Josuttis, Nicolai M. (1999). The C++ Standard Library. Addison-Wesley. ISBN 0-201-37926-0.

Notes

[edit]
  1. ^ a b c Josuttis, Nicolai (1999). C++ Standard Library - A Tutorial and Reference. Addison-Wesley.
  2. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.1 Container requirements [lib.container.requirements] para. 4
  3. ^ Stepanov, Alexander A. (2015). From mathematics to generic programming. Daniel E. Rose. Upper Saddle River, NJ. ISBN 978-0-13-349179-1. OCLC 898036481.{{cite book}}: CS1 maint: location missing publisher (link)
  4. ^ ISO/IEC 14882 ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4 Class template vector (lib.vector) paragraph.1 (PDF) (Technical report). ISO/IEC. 2003. p. 489. Archived from the original (PDF) on 25 February 2022. elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
  5. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.3 vector modifiers [lib.vector.modifiers] para. 1
  6. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.2 vector capacity [lib.vector.capacity] para. 5
  7. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.2 vector capacity [lib.vector.capacity] para. 2
  8. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.4.3 vector modifiers [lib.vector.modifiers] para. 3
  9. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.5 Class vector<bool> [lib.vector.bool] para. 1
  10. ^ "vector<bool>: More Problems, Better Solutions" (PDF). August 1999. Retrieved 28 November 2017.
  11. ^ "A Specification to deprecate vector<bool>". March 2007. Retrieved 28 November 2017.
  12. ^ ISO/IEC (2003). ISO/IEC 14882:2003(E): Programming Languages - C++ §23.2.5 Class vector<bool> [lib.vector.bool] para. 2
  13. ^ "96. Vector<bool> is not a container". Retrieved 28 June 2018.
乙型肝炎表面抗体阳性是什么意思 睡前一杯牛奶有什么好处 天秤座什么性格 榴莲吃了对身体有什么好处 金牛座女和什么星座最配
过敏什么东西不能吃 乙肝核心抗体是什么意思 大悲咒是什么意思 武夷山岩茶属于什么茶 牛筋面是用什么做的
放下身段是什么意思 浩特是什么意思 母亲属虎孩子属什么好 背厚是什么原因造成的 以什么
钯金是什么金 8月10日什么星座 星期三打喷嚏代表什么 内膜薄是什么意思 预警是什么意思
放低姿态是什么意思hcv9jop7ns5r.cn 头发掉的多是什么原因hcv8jop4ns2r.cn 什么泉水hcv8jop4ns0r.cn 处暑的含义是什么意思imcecn.com 女生为什么会痛经hcv8jop6ns3r.cn
疥疮是什么hcv8jop6ns5r.cn 头皮上长疣是什么原因造成的hcv8jop1ns0r.cn 肺结节是一种什么病cl108k.com 解辣喝什么hcv8jop8ns3r.cn 胎盘位于子宫后壁是什么意思wuhaiwuya.com
红细胞分布宽度偏高是什么意思hcv9jop3ns9r.cn 早泄吃什么药见效dayuxmw.com 周杰伦是什么星座hcv9jop4ns9r.cn 晚上喝牛奶有什么好处和坏处hcv8jop2ns8r.cn 中秋节送什么好hcv7jop5ns0r.cn
单核细胞百分比偏高是什么原因aiwuzhiyu.com 时令是什么意思gangsutong.com 祭是什么意思hcv9jop5ns5r.cn 手背有痣代表什么hcv9jop5ns6r.cn 严什么的作风hcv7jop5ns6r.cn
百度