In C++, it is better to use vectors than dynamic arrays because a vector always knows its own size. C-style arrays are better suited to static arrays where the size is always known in advance. The following demonstrates how a vector might be used within a class.
#include<iostream>
#include<vector>
class foo
{
public:
std::vector<int>& operator+= (int data){ m_data.push_back(data); return(m_data);}
int operator[] (size_t element)const{
ASSERT(element<m_array.size());
return( m_array[element]; }
const size_t size()const{return(m_data.size());}
private:
std::vector<int> m_data;
}
int main()
{
foo f;
f += 42;
f += 9;
for(int i=0; i<f.size(); ++i)
std::cout<<f[i]<<std::endl;
}
Output:
42
9
Chat with our AI personalities
#include <iostream>
using std::cout;
using std::endl;
...
int main()
{
const int arraySize = 5;
double myArray [arraySize] = {0.0};
//Enter elements
...
//Display elements
for (int i = 0; i < arraySize; i++)
{
cout << myArray[i] << endl;
}
...
}
int array[10] = {...}; for (int i = 0; i < 10; ++i) { if (i % 2 == 0) array[i] += 5; else array[i] -= 10; }
The lowest subscript of an array in C, or C++ is 0.
If the array is static it can declared in the structure itself: struct myArrayTag { int num[12]; // array of 12 integers (e.g., 48 bytes). } myArray; If it is dynamic then you must use a pointer and allocate the array outside the structure. You should also maintain a variable in the structure to keep track of how many elements the array currently has: struct myBufferTag { int * array; // Pointer to array of integers. int size; // Size of array (number of elements); } myBuffer;
To determine if an array is symmetric, the array must be square. If so, check each element against its transpose. If all elements are equal, the array is symmetric.For a two-dimensional array (a matrix) of order n, the following code will determine if it is symmetric or not:templatebool symmetric(const std::array& matrix){for (size_t r=0 ; r
yes