Difference between revisions of "Tmp2"

From assela Pathirana
Jump to navigationJump to search
Line 23: Line 23:
     cin >> tmp;
     cin >> tmp;
     a.push_back(tmp);
     a.push_back(tmp);
}
|}
a.erase();
a.erase();
</source>
</source>
|}
|}

Revision as of 15:38, 9 April 2007

Good practice in Coding (in C++/C)

  • Use pointers sparingly, there are many situations where they have good alternatives. Make a concious effort to find these alternatives if at all possible. One good example is use of vectors instead of dynamic arrays.
int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0;i<n;i++){
    cin >> a[i];
}
. . .  
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.
vector <int> a;
int n;           // Size needed for array
cin >> n;        // Read in the size
for (int i=0;i<n;i++){
    int tmp;
    cin >> tmp;
    a.push_back(tmp);
|}
a.erase();