??xml version="1.0" encoding="utf-8" standalone="yes"?>
1. To C++ programmer, for example, a pointer to a pointer looks a little funny. Why, we wonder, wasn’t a reference to a pointer used instead?
const char chr[] = "chenzhenshi&guohonghua";
const char* pchr = chr;
const char** ppchr = &pchr;
const char*& rpchr = pchr; // a reference to a pointer
std::cout << pchr << ' ' << *ppchr << ' ' << rpchr << std::endl;
2. C is a fairly simple language. All it really offers is macros, pointers, structs, arrays, and functions. No matter what the problem is, the solution will always boil down to macros, pointers, structs, arrays, and functions. Not so in C++. The macros, pointers, structs, arrays and functions are still there, of course, but so are private and protected members, function overloading, default parameters, constructors and destructors, user-defined operators, inline functions, references, friends, templates, exceptions, namespaces, and more. The design space is much richer in C++ than it is in C: there are just a lot more options to consider.
3. The Item might better be called “prefer the compiler to the preprocessor?
4. const char* pc;
pc = a1;
std::cout << pc << std::endl;
pc = a2;
std::cout << pc << std::endl;
const char* const pcc = "a const pointer to a const char array";
std::cout << pcc << std::endl;
// error C2166: l-value specifies const object
// pcc = a1; // error!
std::cout << pcc << std::endl;
5. You can define a const variable in a class, but it must be static const, and have a definition in an implementation file.
// .h file
class try_const
{
public:
static const int num;
};
// .cxx file
const int try_const::num = 250;
6. You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using an inline function.
Template <class type>
Inline const type& max (const type& a, const type& b)
{
Return a > b ? a : b ;
}
7. Given the availability of consts and inlines, your need for the preprocessor is reduced, but it's not completely eliminated. The day is far from near when you can abandon #include, and #ifdef/#ifndef continue to play important roles in controlling compilation. It's not yet time to retire the preprocessor, but you should definitely plan to start giving it longer and more frequent vacations.
8. scanf and printf are not type-safe and extensible.
9. In particular, if you #include <iostream>, you get the elements of the iostream library ensconced within the namespace std (see Item 28), but if you #include <iostream.h>, you get those same elements at global scope. Getting them at global scope can lead to name conflicts, precisely the kinds of name conflicts the use of namespaces is designed to prevent.
10. The problem with malloc and free(and their variants) is simple : they don’t know about constructors and destructors.
11. free 操作不会(x)调用析构函数Q如果指针所指对象本w又分配?jin)内存,则?x)造成内存丢失?/span>
12. Memory management concerns in C++ fall into two general camps: getting it right and making it perform efficiently.
13. When you use new, two things happen. First, memory is allocated. Second, one or more constructors are called for that memory. When you use delete, two other things happen: one or more destructors are called for the memory, then the memory is deallocated.
14. The standard C++ library includes string and vector templates that reduce the need for built-in arrays to nearly zero.
15. Speaking of smart pointers, one way to avoid the need to delete pointer members is to replace those members with smart pointer objects like the standard C++ Library’s auto_ptr.
让我们回q头ȝ看这样一个基本问题:(x)Z么有必要写自q operator new ?/span> operator delete Q答案通常是:(x)Z(jin)效率。缺省的 operator new ?/span> operator delete h非常好的通用性,它的q种灉|性也使得在某些特定的场合下,可以q一步改善它的性能。尤其在那些需要动态分配大量的但很的对象的应用程序里Q情冉|是如此?/span>
int* pi = new int(0);
if
( pi != 0 )
delete pi;
说明Q如果指针操作数被设|ؓ(f)0Q则C++保证delete表达式不?x)调用操作?span lang="EN-US">delete()。所以没有必要测试其是否?span lang="EN-US">0?span lang="EN-US">
?span lang="EN-US">delete表达式之后,pi被称作空(zhn)指针,x向无效内存的指针。空(zhn)指针是E序错误的根源,对象释放后,该指针讄?span lang="EN-US">0?span lang="EN-US">
2Q?span lang="EN-US">auto_ptr
auto_ptr?span lang="EN-US">C++标准库提供的cL板,它可以帮助程序员自动理?span lang="EN-US">new表达式动态分配的单个对象Q但是,它没有对数组理提供cM支持。它的头文g为:(x)
?span lang="EN-US">auto_ptr对象的生命期l束Ӟ动态分配的对象被自动释放?span lang="EN-US">
auto_ptrcL板背后的主要动机是支持与普通指针类型相同的语法Q但是ؓ(f)auto_ptr对象所指对象的释放提供自动理。例Q?span lang="EN-US">
auto_ptr
cL板支持所有权概念Q当一?span lang="EN-US">auto_ptr对象被用另一?span lang="EN-US">auto_ptr对象初始化赋值时Q左边被赋值或初始化的对象拥有了(jin)I闲存储区内底层对象的所有权Q而右边的auto_ptr对象?font color="#ff0000">撤消所有责?/font>。例Q?span lang="EN-US">
判断是否指向一个对象,例:(x)
3Q数l的动态分配与释放
使用C++标准?span lang="EN-US">string,避免使用C风格字符串数l?span lang="EN-US">
为避免动态分配数l的内存理带来的问题,一般徏议用标准库vector?span lang="EN-US">list?span lang="EN-US">string容器cd?span lang="EN-US">
4Q常量对象的动态分配与释放
可以使用new表达式在I闲存储区内创徏一?span lang="EN-US">const对象Q例Q?span lang="EN-US">
我们不能在空闲存储区创徏内置cd元素?span lang="EN-US">const数组Q原因是Q我们不能初始化?span lang="EN-US">new表达式创建的内置cd数组的元素。例Q?span lang="EN-US">
5
Q定?span lang="EN-US">new表达?span lang="EN-US">
new表达式的W三UŞ式允许程序员要求对象创建在已经被分配好的内存中。称为:(x)定位new表达式(placement new expression)。程序员?span lang="EN-US">new表达式中指定待创建对象所在的内存地址。如下所C:(x)
new Q?span lang="EN-US">place_address) type-specifier
注意Q?span lang="EN-US">place_address必须是个指针Q必d含头文g<new>。这设施允许程序员预分配大量的内存Q供以后通过q种形式?span lang="EN-US">new表达式创建对象。例如:(x)
1. A declaration tells compilers about the name and type of an object, function, class, or template, but it omits certain details.
2. A definition, on the other hand, provides compilers with the details. For an object, the definition is where compilers allocate memory for the object. For a function or a function template, the definition provides the code body. For a class or a class template, the definition lists the members of the class or template.
3. When you define a class, you generally need a default constructor if you want to define arrays of objects.Incidentally, if you want to create an array of objects for which there is no default constructor, the usual ploy is to define an array of pointers instead. Then you can initialize each pointer separately by using new.
4. Probably the most important use of the copy constructor is to define what it means to pass and return objects by value.
5. From a purely operational point of view, the difference between initialization and assignment is that the former is performed by a constructor while the latter is performed by operator=. In other words, the two processes correspond to different function calls. The reason for the distinction is that the two kinds of functions must worry about different things. Constructors usually have to check their arguments for validity, whereas most assignment operators can take it for granted that their argument is legitimate (because it has already been constructed). On the other hand, the target of an assignment, unlike an object undergoing construction, may already have resources allocated to it. These resources typically must be released before the new resources can be assigned. Frequently, one of these resources is memory. Before an assignment operator can allocate memory for a new value, it must first deallocate the memory that was allocated for the old value.
6. These different casting forms serve different purposes:
const_cast is designed to cast away the constness of objects and pointers, a topic I examine in Item 21.
dynamic_cast is used to perform "safe downcasting," a subject we'll explore in Item 39.
reinterpret_cast is engineered for casts that yield implementation-dependent results, e.g., casting between function pointer types. (You're not likely to need reinterpret_cast very often. I don't use it at all in this book.)
static_cast is sort of the catch-all cast. It's what you use when none of the other casts is appropriate. It's the closest in meaning to the conventional C-style casts.
问题Q?br />
有如下两个代码文Ӟ(x)
// 20060816_operator.cxx
// 20060816_operator.h
用上面两个文件徏立工E,vc6.0下编译会(x)出错。报告如下:(x)
--------------------Configuration: 20060816_operator - Win32 Debug--------------------
Compiling...
20060816_operator.cxx
f:\ghh_project\cxxdetail\20060816_operator.h(24) : error C2248: '_ghh' : cannot access private member declared in class 'Honghua'
f:\ghh_project\cxxdetail\20060816_operator.h(19) : see declaration of '_ghh'
F:\ghh_project\CxxDetail\20060816_operator.cxx(8) : error C2593: 'operator <<' is ambiguous
Error executing cl.exe.
20060816_operator.exe - 2 error(s), 0 warning(s)
解决:
1Q?span style="FONT: 7pt 'Times New Roman'">
调整名字I间声明和自定义头文件的ơ序Q如下:(x)2Q?span style="FONT: 7pt 'Times New Roman'"> 把类定义于标准名字之内,20060816_operator.h文g修改如下Q不推荐Q?br />
3Q?span style="FONT: 7pt 'Times New Roman'"> 使用头文?/span>iostream.h代替iostream,比较落后的方式(不推?/span>!Q?br />
4Q?span style="FONT: 7pt 'Times New Roman'"> M时候都不?/span>using namespace 声明Q这是只需要修?/span>20060816_operator.cxx文g如下Q?br />
体会(x)Q?br /> 名字I间本来是Z(jin)解决名字冲突问题而引入,以标准库不受外界媄(jing)响。在q个意义上来_(d)using namespace std;不是可以随意使用的语句,应该考虑到它的位|对E序的可能媄(jing)响,而最d的杜l错误的解决办法是在M时候Q何情况下都不使用此语句!
1 #include <vector>
2 void assign( size_type num, const TYPE& val );
3 void assign( input_iterator start, input_iterator end );
The assign() function either gives the current vector the values from start to end, or gives it num copies of val.
This function will destroy the previous contents of the vector.
For example, the following code uses assign() to put 10 copies of the integer 42 into a vector:
vector<int> v; v.assign( 10, 42 ); for( int i = 0; i < v.size(); i++ ) { cout << v[i] << " "; } cout << endl;
The above code displays the following output:
42 42 42 42 42 42 42 42 42 42
The next example shows how assign() can be used to copy one vector to another:
vector<int> v1; for( int i = 0; i < 10; i++ ) { v1.push_back( i ); } vector<int> v2; v2.assign( v1.begin(), v1.end() ); for( int i = 0; i < v2.size(); i++ ) { cout << v2[i] << " "; } cout << endl;
When run, the above code displays the following output:
0 1 2 3 4 5 6 7 8 9
1 #include <vector>
2 TYPE& back();
3 const TYPE& back() const;
The back() function returns a reference to the last element in the vector.
For example:
vector<int> v; for( int i = 0; i < 5; i++ ) { v.push_back(i); } cout << "The first element is " << v.front() << " and the last element is " << v.back() << endl;
This code produces the following output:
The first element is 0 and the last element is 4
#include <vector> TYPE& at( size_type loc ); const TYPE& at( size_type loc ) const;
The at() function returns a reference to the element in the vector at index loc. The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector.
For example, consider the following code:
vector<int> v( 5, 1 ); for( int i = 0; i < 10; i++ ) { cout << "Element " << i << " is " << v[i] << endl; }
This code overrunns the end of the vector, producing potentially dangerous results. The following code would be much safer:
vector<int> v( 5, 1 ); for( int i = 0; i < 10; i++ ) { cout << "Element " << i << " is " << v.at(i) << endl; }
Instead of attempting to read garbage values from memory, the at() function will realize that it is about to overrun the vector and will throw an exception.
#include <vector> size_type capacity() const;
The capacity() function returns the number of elements that the vector can hold before it will need to allocate more space.
For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:
vector<int> v1(10); cout << "The capacity of v1 is " << v1.capacity() << endl; vector<int> v2; v2.reserve(20); cout << "The capacity of v2 is " << v2.capacity() << endl;
When run, the above code produces the following output:
The capacity of v1 is 10 The capacity of v2 is 20
C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.
The capacity() function runs in constant time.
#include <vector> iterator begin(); const_iterator begin() const;
The function begin() returns an iterator to the first element of the vector. begin() should run in constant time.
For example, the following code uses begin() to initialize an iterator that is used to traverse a list:
// Create a list of characters list<char> charList; for( int i=0; i < 10; i++ ) { charList.push_front( i + 65 ); } // Display the list list<char>::iterator theIterator; for( theIterator = charList.begin(); theIterator != charList.end(); theIterator++ ) { cout << *theIterator; }
#include <vector> size_type max_size() const;
The max_size() function returns the maximum number of elements that the vector can hold. The max_size() function should not be confused with the size() or capacity() functions, which return the number of elements currently in the vector and the the number of elements that the vector will be able to hold before more memory will have to be allocated, respectively.
#include <vector> void clear();
The function clear() deletes all of the elements in the vector. clear() runs in linear time.
#include <vector> bool empty() const;
The empty() function returns true if the vector has no elements, false otherwise.
For example, the following code uses empty() as the stopping condition on a (C/C++ Keywords) while loop to clear a vector and display its contents in reverse order:
vector<int> v; for( int i = 0; i < 5; i++ ) { v.push_back(i); } while( !v.empty() ) { cout << v.back() << endl; v.pop_back(); }
#include <vector> iterator end(); const_iterator end() const;
The end() function returns an iterator just past the end of the vector.
Note that before you can access the last element of the vector using an iterator that you get from a call to end(), you'll have to decrement the iterator first. This is because end() doesn't point to the end of the vector; it points just past the end of the vector.
For example, in the following code, the first "cout" statement will display garbage, whereas the second statement will actually display the last element of the vector:
vector<int> v1; v1.push_back( 0 ); v1.push_back( 1 ); v1.push_back( 2 ); v1.push_back( 3 ); int bad_val = *(v1.end()); cout << "bad_val is " << bad_val << endl; int good_val = *(v1.end() - 1); cout << "good_val is " << good_val << endl;
The next example shows how begin() and end() can be used to iterate through all of the members of a vector:
vector<int> v1( 5, 789 ); vector<int>::iterator it; for( it = v1.begin(); it != v1.end(); it++ ) { cout << *it << endl; }
The iterator is initialized with a call to begin(). After the body of the loop has been executed, the iterator is incremented and tested to see if it is equal to the result of calling end(). Since end() returns an iterator pointing to an element just after the last element of the vector, the loop will only stop once all of the elements of the vector have been displayed.
end() runs in constant time.
#include <vector> iterator erase( iterator loc ); iterator erase( iterator start, iterator end );
The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end). The return value is the element after the last element erased.
The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, dequeues, and strings. The multiple-element version of erase always takes linear time.
For example:
// Create a vector, load it with the first ten characters of the alphabet vector<char> alphaVector; for( int i=0; i < 10; i++ ) { alphaVector.push_back( i + 65 ); } int size = alphaVector.size(); vector<char>::iterator startIterator; vector<char>::iterator tempIterator; for( int i=0; i < size; i++ ) { startIterator = alphaVector.begin(); alphaVector.erase( startIterator ); // Display the vector for( tempIterator = alphaVector.begin(); tempIterator != alphaVector.end(); tempIterator++ ) { cout << *tempIterator; } cout << endl; }
That code would display the following output:
BCDEFGHIJ CDEFGHIJ DEFGHIJ EFGHIJ FGHIJ GHIJ HIJ IJ J
In the next example, erase() is called with two iterators to delete a range of elements from a vector:
// create a vector, load it with the first ten characters of the alphabet vector<char> alphaVector; for( int i=0; i < 10; i++ ) { alphaVector.push_back( i + 65 ); } // display the complete vector for( int i = 0; i < alphaVector.size(); i++ ) { cout << alphaVector[i]; } cout << endl; // use erase to remove all but the first two and last three elements // of the vector alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 ); // display the modified vector for( int i = 0; i < alphaVector.size(); i++ ) { cout << alphaVector[i]; } cout << endl;
When run, the above code displays:
ABCDEFGHIJ ABHIJ
#include <vector> TYPE& front(); const TYPE& front() const;
The front() function returns a reference to the first element of the vector, and runs in constant time.
#include <vector> iterator insert( iterator loc, const TYPE& val ); void insert( iterator loc, size_type num, const TYPE& val ); template<TYPE> void insert( iterator loc, input_iterator start, input_iterator end );
The insert() function either:
Note that inserting elements into a vector can be relatively time-intensive, since the underlying data structure for a vector is an array. In order to insert data into an array, you might need to displace a lot of the elements of that array, and this can take linear time. If you are planning on doing a lot of insertions into your vector and you care about speed, you might be better off using a container that has a linked list as its underlying data structure (such as a List or a Deque).
For example, the following code uses the insert() function to splice four copies of the character 'C' into a vector of characters:
// Create a vector, load it with the first 10 characters of the alphabet vector<char> alphaVector; for( int i=0; i < 10; i++ ) { alphaVector.push_back( i + 65 ); } // Insert four C's into the vector vector<char>::iterator theIterator = alphaVector.begin(); alphaVector.insert( theIterator, 4, 'C' ); // Display the vector for( theIterator = alphaVector.begin(); theIterator != alphaVector.end(); theIterator++ ) { cout << *theIterator; }
This code would display:
CCCCABCDEFGHIJ
Here is another example of the insert() function. In this code, insert() is used to append the contents of one vector onto the end of another:
vector<int> v1; v1.push_back( 0 ); v1.push_back( 1 ); v1.push_back( 2 ); v1.push_back( 3 ); vector<int> v2; v2.push_back( 5 ); v2.push_back( 6 ); v2.push_back( 7 ); v2.push_back( 8 ); cout << "Before, v2 is: "; for( int i = 0; i < v2.size(); i++ ) { cout << v2[i] << " "; } cout << endl; v2.insert( v2.end(), v1.begin(), v1.end() ); cout << "After, v2 is: "; for( int i = 0; i < v2.size(); i++ ) { cout << v2[i] << " "; } cout << endl;
When run, this code displays:
Before, v2 is: 5 6 7 8 After, v2 is: 5 6 7 8 0 1 2 3
#include <vector> vector(); vector( const vector& c ); vector( size_type num, const TYPE& val = TYPE() ); vector( input_iterator start, input_iterator end ); ~vector();
The default vector constructor takes no arguments, creates a new instance of that vector.
The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.
The third constructor creates a vector with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a vector consisting of five copies of the integer 42:
vector<int> v1( 5, 42 );
The last constructor creates a vector that is initialized to contain the elements between start and end. For example:
// create a vector of random integers cout << "original vector: "; vector<int> v; for( int i = 0; i < 10; i++ ) { int num = (int) rand() % 10; cout << num << " "; v.push_back( num ); } cout << endl; // find the first element of v that is even vector<int>::iterator iter1 = v.begin(); while( iter1 != v.end() && *iter1 % 2 != 0 ) { iter1++; } // find the last element of v that is even vector<int>::iterator iter2 = v.end(); do { iter2--; } while( iter2 != v.begin() && *iter2 % 2 != 0 ); cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl; cout << "new vector: "; vector<int> v2( iter1, iter2 ); for( int i = 0; i < v2.size(); i++ ) { cout << v2[i] << " "; } cout << endl;
When run, this code displays the following output:
original vector: 1 9 7 9 2 7 2 1 9 8 first even number: 2, last even number: 8 new vector: 2 7 2 1 9
All of these constructors run in linear time except the first, which runs in constant time.
The default destructor is called when the vector should be destroyed.
#include <vector> void pop_back();
The pop_back() function removes the last element of the vector.
pop_back() runs in constant time.
#include <vector> void push_back( const TYPE& val );
The push_back() function appends val to the end of the vector.
For example, the following code puts 10 integers into a list:
list<int> the_list; for( int i = 0; i < 10; i++ ) the_list.push_back( i );
When displayed, the resulting list would look like this:
0 1 2 3 4 5 6 7 8 9
push_back() runs in constant time.
#include <vector> reverse_iterator rbegin(); const_reverse_iterator rbegin() const;
The rbegin() function returns a reverse_iterator to the end of the current vector.
rbegin() runs in constant time.
#include <vector> reverse_iterator rend(); const_reverse_iterator rend() const;
The function rend() returns a reverse_iterator to the beginning of the current vector.
rend() runs in constant time.
#include <vector> void reserve( size_type size );
The reserve() function sets the capacity of the vector to at least size.
reserve() runs in linear time.
#include <vector> void resize( size_type num, const TYPE& val = TYPE() );
The function resize() changes the size of the vector to size. If val is specified then any newly-created elements will be initialized to have a value of val.
This function runs in linear time.
#include <vector> size_type size() const;
The size() function returns the number of elements in the current vector.
#include <vector> void swap( const container& from );
The swap() function exchanges the elements of the current vector with those of from. This function operates in constant time.
For example, the following code uses the swap() function to exchange the values of two strings:
string first( "This comes first" ); string second( "And this is second" ); first.swap( second ); cout << first << endl; cout << second << endl;
The above code displays:
And this is second This comes first
#include <vector> TYPE& operator[]( size_type index ); const TYPE& operator[]( size_type index ) const; vector operator=(const vector& c2); bool operator==(const vector& c1, const vector& c2); bool operator!=(const vector& c1, const vector& c2); bool operator<(const vector& c1, const vector& c2); bool operator>(const vector& c1, const vector& c2); bool operator<=(const vector& c1, const vector& c2); bool operator>=(const vector& c1, const vector& c2);
All of the C++ containers can be compared and assigned with the standard comparison operators: ==, !=, <=, >=, <, >, and =. Individual elements of a vector can be examined with the [] operator.
Performing a comparison or assigning one vector to another takes linear time. The [] operator runs in constant time.
Two vectors are equal if:
Comparisons among vectors are done lexicographically.
For example, the following code uses the [] operator to access all of the elements of a vector:
vector<int> v( 5, 1 ); for( int i = 0; i < v.size(); i++ ) { cout << "Element " << i << " is " << v[i] << endl; }
Vectors are more powerful than arrays because the number of functions that are available for accessing and modifying vectors. Unfortunately, the [] operator still does not provide bounds checking. There is an alternative way of accessing the vector, using the function at, which does provide bounds checking at an additional cost. Let's take a look at several functions provided by the vector class:
also, there are several basic operators defined for the vector class:
= Assignment replaces a vector's contents with the contents of another == An element by element comparison of two vectors [] Random access to an element of a vector (usage is similar to that of the operator with arrays.) Keep in mind that it does not provide bounds checking.
Let's take a look at an example program using the vector class:
Summary of Vector Benefits1 #include <iostream>
2 #include <vector>
3 using namespace std;
4
5 int main()
6 {
7 vector <int> example; //Vector to store integers
8 example.push_back(3); //Add 3 onto the vector
9 example.push_back(10); //Add 10 to the end
10 example.push_back(33); //Add 33 to the end
11 for(int x=0; x<example.size(); x++)
12 {
13 cout<<example[x]<<" "; //Should output: 3 10 33
14 }
15 if(!example.empty()) //Checks if empty
16 example.clear(); //Clears vector
17 vector <int> another_vector; //Creates another vector to store integers
18 another_vector.push_back(10); //Adds to end of vector
19 example.push_back(10); //Same
20 if(example==another_vector) //To show testing equality
21 {
22 example.push_back(20);
23 }
24 for(int y=0; y<example.size(); y++)
25 {
26 cout<<example[y]<<" "; //Should output 10 20
27 }
28 return 0;
29 }
Vectors are somewhat easier to use than regular arrays. At the very least, they get around having to be resized constantly using new and delete. Furthermore, their immense flexibility - support for any datatype and support for automatic resizing when adding elements - and the other helpful included functions give them clear advantages to arrays.
Another argument for using vectors are that they help avoid memory leaks--you don't have to remember to free vectors, or worry about how to handle freeing a vector in the case of an exception. This simplifies program flow and helps you write tighter code. Finally, if you use the at() function to access the vector, you get bounds checking at the cost of a slight performance penalty.
(?
C++ vector is a container template available with Standard Template Library pack. This C++ vector can be used to store similar typed objects sequentially, which can be accessed at a later point of time. As this is a template, all types of data including user defined data types like struct and class can be stored in this container.
This article explains briefly about how to insert, delete, access the data with respect to the C++ vector. The type stl::string is used for the purposes of explaining the sample code. Using stl::string is only for sample purposes. Any other type can be used with the C++ vector.
The values can be added to the c++ vector at the end of the sequence. The function push_back should be used for this purpose. The <vector> header file should be included in all the header files in order to access the C++ vector and its functions.
The above code adds 4 strings of std::string type to the str_Vector. This uses std:: vector.push_back function. This function takes 1 parameter of the designated type and adds it to the end of the c++ vector.
The elements after being added can be accessed in two ways. One way is our legacy way of accessing the data with vector.at(position_in_integer) function. The position of the data element is passed as the single parameter to access the data.
If we want to access all the data, we can use a for loop and display them as follows.
The std:: vector .size() function returns the number of elements stored in the vector.
The next way is to use the iterator object provided by the STL. These iterators are general purpose pointers allowing c++ programmers to forget the intricacies of object types and access the data of any type.
Removing elements one by one from specified positions in c++ vector is achieved with the erase function.
The following code demonstrates how to use the erase function to remove an element from position 2 in the str_Vector from our sample.
The following sample demonstrates how to use the erase() function for removing elements 2,3 in the str_Vector used in the above sample.
If one wants to remove all the elements at once from the c++ vector, the vector.clear() function can be used.
Different operations and containers support different types of iterator behavior. In fact, there are several different classes of iterators, each with slightly different properties. First, iterators are distinguished by whether you can use them for reading or writing data in the container. Some types of iterators allow for both reading and writing behavior, though not necessarily at the same time.1std::vector<int> myIntVector;
2std::vector<int>::iterator myIntVectorIterator;
The STL approach (use this)1 using namespace std;
2
3 vector<int> myIntVector;
4
5 // Add some elements to myIntVector
6 myIntVector.push_back(1);
7 myIntVector.push_back(4);
8 myIntVector.push_back(8);
9
10 for(int y=0; y<myIntVector.size(); y++)
11 {
12 cout<<myIntVector[y]<<" "; //Should output 1 4 8
13 }
As you might imagine, you can use the decrement operator, --, when working with a bidirectional iterator or a backward operator.1 using namespace std;
2
3 vector<int> myIntVector;
4 vector<int>::iterator myIntVectorIterator;
5
6 // Add some elements to myIntVector
7 myIntVector.push_back(1);
8 myIntVector.push_back(4);
9 myIntVector.push_back(8);
10
11 for(myIntVectorIterator = myIntVector.begin();
12 myIntVectorIterator != myIntVector.end();
13 myIntVectorIterator++)
14 {
15 cout<<*myIntVectorIterator<<" "; //Should output 1 4 8
16 }
17
iterator + nwhere n is an integer. The result will be the element corresponding to the nth item after the item pointed to be the current iterator. This can be a problem if you happen to exceed the bounds of your iterator by stepping forward (or backward) by too many elements.
You can also use the standard arithmetic shortcuts for addition and subtraction, += and -=, with random access iterators. Moreover, with random access iterators you can use <, >, <=, and >= to compare iterator positions within the container.1 vector<int> myIntVector;
2 vector<int>::iterator myIntVectorIterator;
3 myIntVectorIterator = myIntVector.begin() + 2;
which would delete all elements in the vector. If you only wanted to delete the first two elements, you could use1 vector<int>::iterator myIntVectorIterator;
2 myIntVector.erase(myIntVectorIterator.begin(), myIntVectorIterator.end());
Note that various container class support different types of iterators -- the vector class, which has served as our model for iterators, supports a random access iterator, the most general kind. Another container, the list container (to be discussed later), only supports bidirectional iterators.1myIntVector.erase(myIntVectorIterator.begin(), myIntVectorIterator.begin()+2);
class_name<parameters>::iterator
问题已经解决Q帖子摘要如下:(x)
?span lang="EN-US"> ?span lang="EN-US">: 函数模版问题Qؓ(f)什么不能采用多文g方式?span lang="EN-US"> |
|
|
回复?span lang="EN-US">: newgun (
书童) |
2006-8-12 19:34:29 (
得分:
10
) |
Re:
函数模版问题Qؓ(f)什么不能采用多文g方式?span lang="EN-US">
?span lang="EN-US">c++
感受Q得到网友提C,真有一U“柳暗花明又一村”之感,q个所?/span> bug 是这么简单又是这么不单!
一直认为应该是自己的错误,但没惛_是编译器和标准兼Ҏ(gu)的问题。看来自q思维?fn)惯应该有所改变?jin)。应该多角度分析问题Q而不能一味的惛_然?/span>
Ps Q自׃应该考虑试一个新?/span> C++ ~译器了(jin)Q老用 vc Q感觉学的标?/span> C++ 都不U,pq次事g一栗?/span>
喜,相比入学之初Q知识层虽无p换骨之感Q但也小有所学,比已比hQ进步不!
忧,两年硕Q时间紧凑,于学术研I有大成;再现实一点,虽学通信Q但找一满意工作Q仍压力不轻QQ重道q!
ȝ不似本科Q成熟多?jin),也开始考虑现实Q不敢虚度日,但真努力奋斗hQ仍有迷茫不知所Z惑?/span>
不过Q还好,q有一颗虽W拙但还善于反思的脑袋Q虽弯\不少Q但也算一步步的向前行?jin)?/span>
两年Q真的太短!何况已浪费一q光阴哉 ?!
无论Z(jin)工作Qؓ(f)?jin)毕业,q是Z(jin)自己做点成果来,都是该努力的时候了(jin)Q?/span>
不谈人生意义{等大道理,是Z(jin)q求一U生存的基础Q在一只脚已经t入C会(x)的时候,也该明白自己应该做些什么了(jin)Q?/span>
理自己Q做该做的事Q做一个积极的自己Q完善自我!努力Q?img height="20" src="http://www.shnenglu.com/Emoticons/QQ/45.gif" width="20" border="0" />
Ps Q}以此文,做开博纪念,也ؓ(f)我意义上的研二开始的U念?/span>