Chapter 9 Sequential Containers

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.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值