Difference between revisions of "Tmp2"
From assela Pathirana
Jump to navigationJump to search
Line 15: | Line 15: | ||
</source> | </source> | ||
| | | | ||
<source lang=cpp> | |||
vector <int> a; | vector <int> a; | ||
int n; // Size needed for array | int n; // Size needed for array | ||
Line 24: | Line 25: | ||
} | } | ||
a.erase(); | a.erase(); | ||
</source> | |||
|} | |} |
Revision as of 15:35, 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();
|