What is const_iterator

October 20, 2008

A const_iterator is not a const iterator. That is,

const vector<int>::iterator it;

and

vector<int>::const_iterator it;

are different. The first type (const iterator) does not allow any kind of modification of the iterator as well as the contents. That is, both

++it;

and

*it = 40 are illegal.

The second type(const_iterator) allows modification of the iterator, but prevents the contents from getting modified.

So,

++it is legal whereas *it = 40 is illegal.


#include<vector>

using namespace std;

int main()

{  

   vector<int> myVector;

   myVector.push_back(10);

   myVector.push_back(20);

   vector<int>::const_iterator it = myVector.begin();

   ++it;       // Legal 

   *it = 40;   // Illegal

   return 0;

}

Advertisements

How To Watch Pointer As An Array

October 10, 2008

At times, I had been annoyed that the watch window was not showing the whole contents of a pointer array until I found the trick.

Put in the watch window

Starting Address, No of elements to be shown

Please note that in the screen shot attached, the pointer has not been deleted. This may cause memory leaks. I’m sorry that I saw it only now.


How To Make gcc Warn You About Unused Variables

October 9, 2008

Use the option -Wunused with gcc.

gcc MyFile.cpp -Wunused


Constant Pointer And Pointer To A Constant

October 6, 2008

The keyword const specifies that you can not change the value of the variable. When it comes to pointers, we can have two types of constants.

Constant Pointer

It prevents you from changing the pointer from one memory location to another. However, you can change the contents of the pointer.

   int myInt = 10;
   int* const pInt = &myInt;  // Constant pointer
   int myNewInt = 20;
   pInt = &myNewInt; //Illegal 
   *pInt = 30; // Legal

Pointer to a constant

It prevents you from changing the contents of the memory location. However, you can reassign the pointer to a new memory location.

   int myInt = 10;
   const int* pInt = &myInt;  // Pointer to a constant
   int myNewInt = 20;
   pInt = &myNewInt; //Legal 
   *pInt = 30; // Illegal