Creating an Array: Difference between revisions
Content added Content deleted
(→C: Delete.) |
(→C++: Delete everything except Qt and MFC.) |
||
Line 158: | Line 158: | ||
==[[C++]]== |
==[[C++]]== |
||
Using dynamically-allocated (i.e. [[Heap]]) memory: |
|||
<lang cpp> const int n = 10; |
|||
try { |
|||
int* myArray = new int[n]; |
|||
myArray[0] = 1; |
|||
myArray[1] = 2; |
|||
delete[] myArray; |
|||
myArray = NULL; |
|||
} catch (std::bad_alloc a) { |
|||
std::cerr << "allocation failed" << std::endl; |
|||
}</lang> |
|||
Using fixed (i.e. [[System stack|Stack]]) memory: |
|||
<lang cpp> int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */</lang> |
|||
Using boost::array |
|||
<lang cpp> boost::array<int,3> myArray2 = { 1, 2, 0}; </lang> |
|||
<nowiki>{{libheader|STL}}</nowiki> |
|||
<lang cpp> // STL |
|||
std::vector<int> myArray3(10); // make array with 10 elements, initialized with 0 |
|||
myArray3[0] = 1; // set first element to 1 |
|||
myArray3[1] = 2; // set second element to 2 |
|||
myArray3.push_back(11); // append another element with value 11 |
|||
myArray3.push_back(12); // append another element with value 12 |
|||
// now myArray has 12 elements: 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12 |
|||
</lang> |
|||
<nowiki>{{libheader|Qt}}</nowiki> |
<nowiki>{{libheader|Qt}}</nowiki> |
||
<lang cpp> // Qt |
<lang cpp> // Qt |