answersLogoWhite

0


Best Answer

#include<iostream>

#include<vector>

int main()

{

std::vector<int> v {1, 4, 8, 15, 23}; // initialise array with 5 elements

v.push_back (42); // add a 6th element

for (auto i : v) std::cout << i << std::endl; // print array elements

}

User Avatar

Wiki User

9y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

7y ago

An array is a contiguous block of memory divided into one or more elements of the same data type. As such, each element is the same length (in bytes). Any data type can be stored in an array -- including another array.

There are several ways to instantiate an array in C++, both statically (at compile time, on the stack) and dynamically (at runtime, on the heap or free store).

The most primitive type of array is the C-style array. The following shows two ways to instantiate a 10-element C-style array of type int:

int a[10] {}; // static allocation

size_t size = 10;

int* b = new int[size] {}; // dynamic allocation

delete [] b;

Note that static arrays must use a constant expression to set the number of elements whereas dynamic arrays can use a variable expression. Note also that static arrays are deleted automatically as soon as they fall from scope but dynamic arrays must be manually deleted using the delete [] operator.

The {} after the declaration is an empty initialiser. This forces the array to initialise all the elements in the array to the value zero. This is required when instantiating arrays of primitive data types (such as int) otherwise they will be left in an uninitialised state. However, you can also provide specific values for each element through the initialiser:

int a[10] {0,1,2,3,4,5,6,7,8,9};

size_t size = 10;

int* b = new int[size] {0,1,2};

delete [] b;

The {0,1,2} initialises the first three elements to the specified values. The seven remaining elements will be initialised to zero.

Since the elements in both arrays are declared variable, you can alter their values. There are two ways to achieve this, either by using pointer arithmetic or by using the subscript operator. Both methods require a zero-based offset. Thus to change the fifth element, we use the offset 4.

// pointer arithmetic

*(a + 4) = 42;

*(b + 4) = 42;

// subscript operator

a[4] = 42;

b[4] = 42;

Both methods achieve the same thing, assigning the value 42 to the fifth element. Clearly the subscript operator is easier to read, however this is merely sugar-coating for the underlying pointer arithmetic. Even if you never use pointer arithmetic, it's important to realise the relationship between pointers and arrays.

The name of the array, a, is a reference to the start address of the array, which is also the address of the first element, a[0]. Since each element is an int, the compiler knows that a + 4 really means a + (4 * sizeof (int)) bytes. However, we don't need to include the element size because the size can be inferred from the array type.

By contrast, b is a pointer to an array of int. The array itself has no name (b is the pointer's name, not the array's name), but the variable b holds the start address of the array. When we use the subscript operator on an array pointer, we get a reference to the start address of the array offset by the given subscript. So to all intents and purposes, we can regard b as being the name of the array, even though the array is really anonymous. The upshot is that we can use the same syntax whether using a static or dynamic array, whether using pointer arithmetic or a subscript operator.

C-style static arrays can also be created using the std::array sequence container available via the standard template library (STL). This was introduced with C++11 (in C++98 you should find it in the std::tr1 namespace; consult C++ Technical Report 1 for more information).

The std::array container is really no different to a C-style static array, however the main advantage is that a std::array knows its own size and can therefore perform its own range checks. With C-style arrays, there are no range checks so it's easy to inadvertently access memory outside of the array which could lead to a memory corruption.

The std::array container can be instantiated as follows:

std::array<int, 10> c {};

And you can use it just as you would a C-style array:

c[4] = 42;

C-style dynamic arrays are dynamic in two senses. The first is that they are obviously allocated at runtime on the free store. The second is that they can change size; they are not fixed size like a std::vector or C-style static array. The problem is that when you want to change the size of a dynamic array, you first need to allocate new memory of the required size, copy the current elements from the old array, and finally delete the old array.

Although you could use malloc, realloc and free instead of the new [] and delete [] operators, there is no real advantage in doing so. The realloc function occasionally copies the array anyway so the benefit of reallocating are minimal. Plus it's rarely a good idea to mix C++ allocations (new/delete) with C-style allocations (malloc/free).

An altogether better approach is to use the std::vector from the STL. This is the dynamic version of std::array so it knows its own size and provides range checking. More importantly, it grows naturally. You don't need to worry about memory allocations because you can simply push new values onto the end of the vector and let the vector itself worry about the memory allocation. Vectors occasionally have to allocate new memory just as with C-style dynamic arrays, however they always reserve more memory than they need (by a factor of 1.6), so resizing should be relatively rare. You can also specify how much memory to initially reserve. Once the array is filled, you can shrink to eliminate any unused space.

For most arrays you should try and stick to std::array and std::vector since both know their own size and include range-checks. This makes it easier to pass arrays to and from functions and you don't need to worry about the underlying memory allocations. For large arrays, always use std::vector because stack memory is severely limited by comparison. Use std::array for trivial, fixed-size arrays only.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

The primary use of an array is when you need constant time, random access to any element within a collection of elements of the same type. If you don't need random access, a list is more efficient when the number of elements is variable. If the number of elements is fixed, an array uses less memory.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

An array is simply a contiguous block of memory that is divided equally by the number of elements in the array. For instance, a 10-element array of type int is a 40 byte array (assuming a 32-bit int). Each element in the array is accessed via a zero-based offset from the start of the array, such that the second element is at offset 1, and the third at offset 2. Multiplying the offset by the size of an element, and adding this product to the start address of the array, gives the actual address of that element within the array. The array suffix operator [] is used to simplify things by specifying only the zero-based offset (the compiler will translate this notation to an actual address). You are free to use pointer arithmetic or the suffix operator, or even both at the same time, to address elements of an array.

Arrays are used to group similar types of data. Often arrays are one-dimensional data lists or two-dimensional data tables, but you can use as many dimensions as required. Regardless of the number of dimensions, the array can be divided and subdivided to produce separate one-dimensional arrays. For instance, a two-dimensional array is simply a one-dimensional array of one-dimensional arrays.

Arrays can be static or dynamic. Static arrays are allocated on the stack and are typically intended for small arrays. However, the main criteria with a static array is that the number of elements must be constant. Dynamic arrays are allocated on the heap, and are generally intended for larger arrays, but the number of elements can also be variable. However, when increasing the size of a dynamic array, it may not be possible to allocate more memory to the end of the array, in which case new memory must be allocated, and the existing memory copied into it, before releasing the original array. This is an expensive operation, but it is done automatically via the realloc() function in C. However, C programmers are entirely responsible for the memory allocated to an array, just as they are when allocating memory to a pointer (they are, in fact, exactly the same thing).

In C++, dynamic arrays are much easier to work with using a vector. A vector is simply a wrapper for an underlying C-style array, but where the array can be treated as a self-contained object that encapsulates the memory management. You use vectors exactly as you would arrays, including usage of the array suffix operator, but gain the benefit of built-in methods, such as push_back() to add new elements to the end of the array, and clear() to remove all elements from the array. There is also no need to keep track of how many elements are in the array since that aspect is fully encapsulated by the vector object, thus passing dynamic arrays to functions is much simplified (in C, you must pass a pointer to the start of the array, along with the length of the array, to prevent buffer overflows).

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

An array in any language is a contiguous block of memory that contains 1 or more elements of the same type. The array name is a reference to the starting address of the array itself, which is also the same address as the first element in the array. since all elements in the array must be of the same type, any element can be found at start_address+index*sizeof(<typename>), where the index is a zero-based value in the range 0 to n-1 for n elements. Like many other languages, C++ also allows use of the subscript operator [] to access individual elements without the need for pointer arithmetic in your code. Thus the nth element in an array can be found at <array_name>[n-1]. Behind the Scenes, the compiler will convert subscripts to the equivalent pointer arithmetic for you. The upshot is that arrays allow random access to any element in constant time, with time complexity O(1).

This answer is:
User Avatar

User Avatar

Wiki User

14y ago

Arrays have millions of uses, and any good program will have to use them at some point.

Some of them are:

Strings and text. A string/text is a sequence of characters. You need to store them in an array. This:

char text[15] = "Hello World!!!";

Is much easier to use than this:

char char1 = 'H';

char char2 = 'e';

char char3 = 'l';

char char4 = 'l';

char char5 = 'o';

char char6 = '!';

Another use of arrays is when you have a group of variables of the same type. For example:

double average(int count, double* numbers /*array*/){

double avg = 0;

for(int i = 0;i<count;i++){

avg += numbers[i];

}

avg /= count;

return avg;

}

And there are many other uses of arrays as well.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

Generally, An array is a systematic arrangement of objects, usually in rows and columns.

Array data type is used in a programming language to specify a variable that can be indexed.

In easy words, it is a list of variables of same data type.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago
The uses for an array in C++ are exactly the same as for any language. They are used whenever you require constant-time, random access to two or more elements of the same type. Ideally, the number of elements should be fairly static as resizing an array can be expensive in terms of performance and memory consumption (the elements of an array must reside in contiguous memory).


In C++, the vector template is the preferred method of declaring an array. This is because a standard array has no knowledge of its own size (how much memory it consumes, which is determined by the number of elements it contains). This means that when you pass an array to a function, you must also pass its size in order to prevent buffer overflows within that function. A vector, on the other hand, encapsulates the array and exposes an interface to that array, including its size. Vectors also include memory management which helps to reduce the performance impact whenever the array is resized.



This answer is:
User Avatar

User Avatar

Wiki User

10y ago

int n[10]; // static array of 10 integers (C and C++)

std::vector<int>; // Dynamic array of int (C++ only)

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What is an array and how do you use them in c and c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

What is the lowest subscript of an array in c plus plus?

The lowest subscript of an array in C, or C++ is 0.


How do you use character in c plus plus?

If you are referring to the character object 'char,' then here are a couple of uses:To create an object, use this:char object = 'a';To create an array of chars, use this:char array[10];To dynamically allocate an array of chars, use this:char array = new char[10];(Don't forget to delete the object with 'delete [] array')


How do you declare a string array and add elements to it in C plus plus?

You cannot add elements to a fixed array in C or C++. If, however, the array is declared as a pointer to an array, you can add elements by allocating a new array, copying/adding elements as needed, reassigning the new array to the pointer, and deallocating the original array.


C plus plus array-based lists?

If you mean an array where each element is a list, then the STL is your friend. To create an array of lists of any type T, use the following declaration: std::vector&lt;std::list&lt;T&gt;&gt; my_array_of_lists;


What is the c plus plus command to read a line?

You can use cin which located in iostream.h You have to use certain data type to read string, for instance, array of char


Array implementation of priority queue example program in c plus plus?

yes


What is multidimensional array in c plus plus?

A multidimensional array in C or C++ is simply an array of arrays, or an array of an array of arrays, etc. for however many dimensions you want. int a; // not an array int a[10]; // ten int a's int a[10][20]; // twenty int a[10]'s, or 200 int a's int a[10][20][30]; // and so on and so forth...


Is it possibly to return an array of strings in a function without using pointers in C plus plus?

No.


How do you use in array?

cod a program student degree array in c language


Can you help me with the C plus plus code of the program which has 10 index of array it adds 5 into every even elements of the array and then it subtracts 10 into the odd elements of the array?

int array[10] = {...}; for (int i = 0; i &lt; 10; ++i) { if (i % 2 == 0) array[i] += 5; else array[i] -= 10; }


How do you swap two adjecent no in array in c?

Option 1) Use a temporary variable: int x = array[i]; array[i] = array[i+1]; array[i+1] = x; Option 2) Use bit operators: array[i] ^= array[i+1] ^= array[i];


How do you make a C plus plus program that arrange the the numbers in ascending order?

Heres something i whipped up in a hurry... This uses the Bubble Sort method found (related links) #include &lt;iostream&gt; using namespace std; int main(int argc, const char* argv) { int arraysize = 5; //Unsorted array size int array [] = { 5, 3, 4, 2, 1 }; //The array of numbers itself //Display the unsorted array cout &lt;&lt; "Before: {"; for (int c=0; c &lt;= arraysize; c++) { cout &lt;&lt; array[c]; if (c != arraysize) { cout &lt;&lt; ","; } } cout &lt;&lt; "}" &lt;&lt; endl; //Acctually sort the array int tmp=0; //Used for swaping values for (int loop=0; loop &lt;= (arraysize - 1); loop++) { for (int c=0; c &lt;= (arraysize - 1); c++) //The sort loop { if (array[c] &gt; array[c + 1]) { //Swaps the two values in the array tmp = array[c]; array[c] = array[c + 1]; array[c + 1] = tmp; //Cleanup tmp = 0; } } } //Display the sorted array cout &lt;&lt; "After: {"; for (int c=0; c &lt;= arraysize; c++) { cout &lt;&lt; array[c]; if (c != arraysize) { cout &lt;&lt; ","; } } cout &lt;&lt; "}" &lt;&lt; endl; return 0; }