Chapter 9 Sequential Containers

本文详细介绍了C++中各种容器(如vector、list、deque等)和字符串类(string)的基本操作,包括添加、删除、访问元素、修改字符串内容及比较字符串等核心功能。同时,还探讨了容器适配器(如stack、queue、priority_queue)的应用场景。通过实例代码,清晰展示了如何在实际编程中高效地使用这些内置数据结构。

Sequential Containers

vector    Supports fast random access


list      Supports fast insertion/deletion


deque     Double-ended queue


Sequential Container Adaptors

stack     Last in/First out stack


queue     First in/First out queue


priority_queue   Priority-managed queue


9.3 -- Sequence Container Operations

Operations that Add Elements to a Sequential Container

c.push_back(t)    Adds element with value t to the end of c. Returns void.


c.push_front(t)   Adds element with value t to front of c. Returns void.

                  Valid only for list or deque.


c.insert(p,t)     Inserts element with value t before the element referred to by iterator p. Returns an iterator referring to the element that was added.


c.insert(p,n,t)   Inserts n elements with value t before the element referred to by iterator p. Returns void.


c.insert(p,b,e)   Inserts elements in the range denoted by iterators b and e before the element referred to by iterator p. Returns void.


Beware:

Iterators may be invalidated after doing any insert orpush operation on a vector or deque. When writing loops thatinsert elements into avector or adeque, the program must ensure that the iterator is refreshed on each trip through the loop.

Tips:

Don't cache the iterator returned from end. Inserting or deleting elements in adeque orvector will invalidate the cached iterator.


Sequential Container Size Operations

c.size()        Returns the number of elements in c. Return type is c::size_type.


c.max_size()    Returns maximum number of elements c can contain. Return type is c::size_type.


c.empty()       Returns a bool that indicates whether size is 0 or not.


c.resize(n)     Resize c so that it has n elements. If N < c.size(), the excess elements are discarded. If new elements must be added, they are value initialized.


c.resize(n,t)   Resize c to have n elements. Any elements added have value t.


Beware:

resize can invalidate iterators. A resize operation on avector ordeque potentially invalidates all iterators.


Operations to Access Elements in a Sequential Container

c.back()    Returns a reference to the last element in c. Undefined if c is empty.


c.front()   Returns a reference to the first element in c. Undefined if c is empty.


c[n]        Returns a reference to the element indexed by n.

                     Undefined if n <0 or n >= c.size().

                     Valid only for vector and deque.


c.at(n)     Returns a reference to the element indexed by n. If index is out of range, throws out_of_range exception.

                     Valid only for vector and deque.


Operations to Remove Elements from a Sequential Container

c.erase(p)     Removes element referred to by the iteratorp.

                           Returns an iterator referring to the element after the one deleted, or an off-the-end iterator ifp referred to the last element. Undefined ifp is an off-the-end iterator.


c.erase(b,e)   Removes the range of elements denoted by the iterators b ande.

                           Returns an iterator referring after the last one in the range that was deleted, or an off-the-end iterator ife is itself an off-the-end iterator.


c.clear()      Removes all the elements inc. Returns void.


c.pop_back()   Removes the last element inc. Returns void. Undefined if c is empty.


c.pop_front()  Removes the first element inc. Returns void. Undefined if c is empty.

                           Valid only for list or deque.


Beware:

The erase, pop_front, and pop_back functions invalidate any iterators that refer to the removed elements. Forvectors, iterators to elements after the erasure point are also invalidated. Fordeque, if theerase does not include either the first or last element, all iterators into thedeque are invalidated.


Sequential Container Assignment Operations

c1 = c2        Deletes elements inc1 and copies elements fromc2 intoc1.c1 andc2 must be the same type.


c1.swap(c2)    Swaps contents: After the callc1 has elements that were inc2, andc2 has elements that were inc1.c1 andc2 must be the same type. Execution time usuallymuch faster than copying elements fromc2 toc1.


c.assign(b,e)  Replaces the elements inc by those in the range denoted by iteratorsb ande. The iteratorsb ande must not refer to elements inc.


c.assign(n,t)  Replaces the elements inc byn elements with valuet.


9.4 -- How a vector Grows

To support fast random access, vector elements are stored contiguously -- each element is adjacent to the previous element.

The vector class includes two members, capacity andreserve, that let us interact with the memory-allocation part ofvector's implementation.

Note:

It is important to understand the difference between capacity andsize. Thesize is the number of elements in thevector;capacity is how many it could hold before new space must be allocated.


9.5 -- Deciding Which Container to Use

The vector and deque types provide fast non-sequential access to elements at the cost of making it expensive to add or remove elements anywhere other than the ends of the container. Thelist type supports fast insertion and deletion anywhere but at the cost of making nonsequential access to elements expensive.


9.6 -- strings Revisited

string Operations Introduced in Section 3.2

string s;         Defines a new, empty string named s.


string s(cp);     Defines a new string initialized from the null-terminated C-style string pointed to by cp.


string s(s2);     Defines a new string initialized as a copy of s2.


is >> s;          Reads a whitespace-separated string from the input stream is into s.


os << s;          Writes s to the output stream os.


getline(is, s)    Reads characters up to the first newline from input stream is into s.


s1 + s2           Concatenates s1 and s2, yielding a new string.


s1 += s2          Appends s2 to s1.


Relational Operators        The equality (== and !=) and relational (<, <=, >, and >=) can be used to compare strings. string comparison is equivalent to (case-sensitive) dictionary ordering.


Substring Operation

s.substr(pos, n)     Return a string containing n characters from s starting at pos.


s.substr(pos)        Return a string containing characters from pos to the end of s.


s.substr()           Return a copy of s.


Operations to Modify strings

s.append( args)             Append args to s. Returns reference to s.


s.replace(pos, len, args)   Remove len characters from s starting at pos and replace them by characters formed by args. Returns reference to s.

                                                    

s.replace(b, e, args)       Remove characters in the range denoted by iterators b and e and replace them by args. Returns reference to s.

                                                     

string s("C++ Primer");        // initialize s to "C++ Primer"
s.append(" 3rd Ed.");          // s == "C++ Primer 3rd Ed."
// equivalent to s.append(" 3rd Ed.")
s.insert(s.size(), " 3rd Ed.");

// starting at position 11, erase 3 characters and then insert "4th"
s.replace(11, 3, "4th");          // s == "C++ Primer 4th Ed."
// equivalent way to replace "3rd" by "4th"
s.erase(11, 3);                   // s == "C++ Primer Ed."    string-Specific Version of erase()
s.insert(11, "4th");              // s == "C++ Primer 4th Ed."

Note:

There is no requirement that the size of the text removed and inserted be the same.

string Search Operations

s.find( args)     Find first occurrence of args in s.


s.rfind( args)    Find last occurrence of args in s.


s.find_first_of( args)      Find first occurrence of any character from args in s.


s.find_last_of( args)       Find last occurrence of any character from args in s.


s.find_first_not_of( args)  Find first character in s that is not in args.


s.find_last_not_of( args)   Find last character in s that is not in args.


string compare Operations

s.compare(s2)                    Compare s to s2.


s.compare(pos1, n1, s2)          Compares n1 characters starting at pos1 from s to s2.


s.compare(pos1, n1, s2, pos2, n2)Compares n1 characters starting at pos1 from s to the n2 characters starting at pos2 in s2.


s.compare(cp)                    Compares s to the null-terminated string pointed to by cp.


s.compare(pos1, n1, cp)          Compares n1 characters starting at pos1 from s to cp.


s.compare(pos1, n1, cp, n2)      Compares n1 characters starting at pos1 from s to n2 characters starting from the pointer cp.



9.7 -- Container Adaptors

To use an adaptor, we must include its associated header:

#include <stack>    // stack adaptor
#include <queue>    // both queue and priority_queue adaptors


Operations Supported by the Stack Container Adaptor

s.empty()      Returns true if the stack is empty; false otherwise.


s.size()       Returns a count of the number of elements on the stack.


s.pop()        Removes, but does not return, the top element from the stack.


s.top()        Returns, but does not remove, the top element on the stack.


s.push(item)   Places a new top element on the stack.


Operations Supported by Queues and Priority Queues

q.empty()     Returns true if the queue is empty; false otherwise.


q.size()      Returns a count of the number of elements on the queue.


q.pop()       Removes, but does not return, the front element from the queue.


q.front()     Returns, but does not remove, the front element on the queue.

                          This operation can be applied only to a queue.


q.back()      Returns, but does not remove, the back element on the queue.

                          This operation can be applied only to a queue.


q.top()       Returns, but does not remove, the highest-priority element.

                          This operation can be applied only to a priority_queue.


q.push(item)  Places a new element at the end of the queue or at its appropriate position based on priority in a priority_queue.



### Sequential 的定义与应用 在编程和机器学习领域,“Sequential”通常指代一种特定的模型结构或数据处理方式。以下是其具体含义: #### 1. **在编程中的意义** “Sequential”可以表示按顺序执行的操作流程。例如,在传统的程序设计中,代码通常是按照书写顺序依次运行的。这种线性的执行模式被称为“sequential execution”。这意味着每一步操作都依赖于前一步的结果[^3]。 #### 2. **在机器学习中的意义** 在机器学习框架(如 TensorFlow 或 Keras)中,“Sequential”是一种用于构建神经网络模型的方式。它代表了一种层叠式的架构,其中每一层只连接到下一层,形成一条单一路径的数据流动方向。这种方式非常适合初学者以及简单的任务建模[^1]。 下面是一个使用 Keras 构建 Sequential 模型的例子: ```python from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense model = Sequential() model.add(Dense(32, activation=&#39;relu&#39;, input_dim=100)) model.add(Dense(1, activation=&#39;sigmoid&#39;)) model.compile(optimizer=&#39;rmsprop&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;]) ``` 在这个例子中,`Sequential()` 方法被用来创建一个空的模型对象,随后通过 `add()` 函数逐层添加不同的神经元层。最终编译完成整个模型并准备训练过程[^4]。 需要注意的是,并非所有的深度学习问题都能很好地适应 sequential 结构;对于更复杂的场景比如循环神经网络(RNNs),可能还需要考虑其他类型的拓扑结构来满足需求[^2]。 ### 总结 无论是作为一般意义上的术语还是专属于某些技术栈内的概念,“sequential”始终围绕着次序性和连贯性展开讨论——即如何依据既定规则一步步推进计算逻辑直至达成目标输出。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值