!!!Chapter 3 Library Types (3.3 ~ 3.5)

3.3 Library vector Type

A vector is a collection of objects of a single type, each of which has an associated integer index. To use a vector we must include the appropriate header:

#include <vector>
using std::vector;

A vector is a class template, templates let us write a single class or function definition that can be used on a variety of types. Here is how to define vector objects:

vector<int> ivec;               //holds objects of type int
vector<sales_item> sales_vec;   //holds sales_items

Vector is not a type; it is a template that we can use to define any number of types. Hence, vector<int> and vector<string> are types.

3.3.1 Defining and Initializing vectors

vector<T> v1;               //vector that holds objects of type T; Default constructor v1 is empty
vector<T> v2 (v1);          //V2 is a copy of v1, v2 and v1 should be the same type
vector<T> v3 (n, i);        //V3 has n elements with value i
vector<T> v4 (n);           //v4 has n copies of a value-initialized object 

Because vector grow efficiently, it is usually best to let the vector grow by adding elements to it dynamically as the element values are known. No need to preallocate a given number of elements in a vector!

When we do not specify an element initializer, then the library creates a value initialized element initializer for us:

1. If the vector holds elements of a built-in type, such as int, then the library creates an element initializer with a value of 0;
2. If the vector holds elements of a class type, such as string, that defines its own constructors, then the library uses the value type's default constructor to create the element initializer

vector<int> ivec(10);  //10 elements, each initialized to 0
vector<string> svec(10); //10 elements, each an empty string

*If the classes do not define a default constructor, then we must specify the size and initial element value.

3.3.2 Operations on vectors

v.empty()
v.size()
v.push_back(t)              //Adds element with value t to end of v
v[n]
v1 = v2
v1 == v2
!=, <, <=, >, >=

1. size of vector

empty and size are similar to string operations. size returns a value of size_type defined by corresponding vector type.

// To use size_type, we must name the type in which it is defined
vector<int>::size_type      //ok
vector::size_type           //error

2. Adding elements to vector

//read words from the standard input and store them as elements in a vector
string word;
vector<string> text;
while (cin >> word)
{
   text.push_back(word);
}

3. Subscripting a vector

We can fetch an element using the subscript operator. The vector subscript yields an lvalue so that we may write to it.

// reset the elements in the vector to zero
for (vector<int>::size_type ix = 0; ix != ivec.size(); ++ix)  
ivec[ix]=0;                                           

ps: Here we use size function as loop criteria, because the size of the vector may grow during the for-loop!

Subscripting Does not Add elements!

//Correct way to create a vector with 10 elements
vector<int> ivec;   //empty vector
for (vector<int>::size_type ix = 0; ix != 10; ++ix)
ivec.push_back(ix);  
//Wrong way to create a vector with 10 elements
vector<int> ivec;   //empty vector
for (vector<int>::size_type ix = 0; ix != 10; ++ix)
ivec[ix] = ix;         //disaster: ivec has no elements

3.4 Introducing Iterators

An iterator is a type that lets us examine the elements in a container and navigate from one element to another.

The library defines an iterator type for each of the standard containers. All of the library containers define iterator types but only a few of them support subscripting

Each of the container types, such as vector, defines its own iterator type:

vector<int>::iterator iter;

Each container defines a type named iterator,and that type supports the actions of an iterator.

The begin and end Operations

Each container defines a pair of functions named begin and end that return iterators.

1. Begin will return the first element of the vector (If the vector is not empty). It is same as vector[0].

2. End will return an iterator positioned "one past the end" of the vector. When vector is empty, begin equals to end.

vector<int>::iterator iter = ivec.begin();

Iterator types use the dereference operator (The * operator) to access the element to which the iterator refers.

Iterator use increment operator (++) to advance an iterator to the next element in the container

// iterator returned from end cannot be incremented or dereferenced
*iter = 0;     // assign 0 to the element
++ iter;

Iterator example:

// using iterators to reset all the elements in ivec to 0
for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
*iter = 0;

Two iterators can be compared using either == or !=. Iterators are equal if they refer to the same element.

Vector iterators also support other arithmetic operations (iterator arithmetic):

// add or subtract integral value. generate a new iterator n elements ahead or behind
iter + n;     // n should be vector's size_type  
iter - n;     // or difference_type
// we can also compute the difference of two iterators, and generate a signed integral named difference_type
iter1 - iter2;

we can use iterator arithmetic to move an iterator to an element directly:

vector<int>::iterator mid = vi.begin()+vi.size()/2;

PS: any operation that changes the size of a vector makes existing iterators invalid.

Const_iterator

Each container type also defines a type named const_iterator, which should be used when reading, but not writing to, the container elements.

When we dereference a const_iterator, the value returned is const. We cannot assign to an element with const_iterator.

vector<int> nums(10);
//iterator that is const.
const vector<int>::iterator cit = num.begin();
*cit = 1;       //ok: cit can change its underlying value
++cit;          //error:: cit is const
//const_iterator
vector<int>::const_iterator iter;
++iter;         //ok
*iter = 1;      //error

const vector can only use const_iterator:

const vector<int> nines(10,9);  //const vector, cannot change elements
//error: cit2 could change the element it refers
const vector<int>::iterator cit2 = nines.begin();
//ok
vector<int>::const_iterator it = nines.begin();

3.5 Library bitset Type

The standard library makes it easy to deal with bits through the bitset class. To use a bitset we must include its associated header file:

#include <bitset>
using std::bitset

Bitset class is a class template (like vector), the objects of type bitset differ by size. We specify the size between a pair of angle brackets:

bitset<32> bitvec;   //32 bits, all zero

The bits in a bitset are not named. We refer to them positionally. The bits are numbered from 0. The bit at 0 are referred to as low-orderbits, and the bit at n-1 are high-orderbits.

//Way to initialize a bitset
bitset<n> b;             //b has n bits, each bit is 0
bitset<n> b(u);          //b is a copy of the unsigned long value u
bitset<n> b(s);          //b is a copy of the bits contained in string s
bitset<n> b(s, pos, n);  //b is a copy of the bits in n characters from s starting from position pos

*pos count from 0, so s[5] is the 6th bit in string s.

Initializing bitset from an unsigned value

1. The unsigned value is treated as a bit pattern. The bits in the bitset are a copy of that pattern.

2. If the size of the bitset is greater than the number of bits in an unsigned long, then the remaining high-order bits are set to zero. 

3. If the size of the bits is less than that number of bits, then only the low-order bits from the unsigned value are used.

//bitvec1 is smaller than the initializer
bitset<16> bitvec1 (0xffff);            //bits 0...15 are set to 1
//bitvec2 is same as the initializer
bitset<32> bitvec2 (0xffff);            //bits 0...15 are 1; 16...31 are 0
//bitvec3 is longer than initizlizer
bitset<128> bitvec3 (0xffff);           //bits 0...15 are 1; 16...127 are 0

oxffff represent a 32 bit value: bits 0...15 are 1; 16...31 are 0

Initializing bitset from a string      P103

1. The string represents the bit pattern directly.

2. The bits are read from the string from right to left.

string str("111111100001101");
bitset<8> bitvec5 (str, 5, 4);            //use str[5] till str[8], which is 1100,others are 0
bitset<8> bitvec6 (str, str.size() - 4);  //using last 4 characters
For bitvec5, we use a substring start from str[5]. So the substring is "1100". And we need to initialize bitvec5 from right to left, so bitvec5 = "00110000"

For bitvec6, we did not provide the third parameter, which means we use the characters from the starting position till the end. So the substring is "1101", and bitvec6 = "10110000"

3.5.2 Operations on bitsets      P104

1. Testing the entire bitset

b.any()        //Is any bit in b on?
b.none()       //Are no bits in b on?
b.count()      //Number of bits in b that are on
b.size()       //Number of bits in b
The return value of b.count() and b.size()are size_t. It is defined in cstddefheader, which is the c++ version of stddef.h header form c.
2. Accessing the bits in a bitset
b[pos]         //Access bit in b at position pos
b.test(pos)    //Is bit in b in position pos on?
b.set(pos)     //Turn on bit in b at position pos
b.reset(pos)   //Turn off bit in b at position pos
b.flip(pos)    //Reverse one bit, it is equal to b[pos].flip()

3. Setting the entire bitset

b.set()        
b.reset()
b.flip()
4. Other operations
b.to_ulong()   //Returns an unsigned long with the same bits as in b
This function can be used only if the size ob bitset is <= the size of unsigned long. 

The function is intened to be used when we need to pass a bitset to a C or pre-Standard C++ program.

os << b     //print the bits in b to the stream os
bitset<16> bitvec2(0xff);     //bits 0...7 are 1; 8...15 are0
cout << bitvec2 <<endl;       //Output is "0000000011111111"

<pre>
 
 
 
 
 
 
 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值