//declare array (indexes are from 0 to 999 (1000 elements), be careful)
int arr[1000];
int num;
cout << "How many numbers will you write?" << endl;
cin >> num;
//read NUM integers and write them into array
for(int i=0; i<num; ++i) {
cin >> arr[i];
}
In this example we have read num elements from the user and stored them into array. If we wanted to read more than 1000 values, we would overflow the array, resulting in undefined behaviour. The place for 1000 integers is defined when program is compiled and cannot be changed at runtime. This can be overcame by dynamic memory allocation. (See below)
int num;
cout << "How many numbers will you write?" << endl;
cin >> num;
int *arr=new int[num];
for (int i=0; i<num; ++i) {
cin >> arr[i];
}
delete arr[];
Firstly, we ask an user to tell us, how many numbers he wants to input and then we read them. This is a lot better, we can allocate the required amount of memory at runtime instead of declaring fixed array of a very big amount of integers, hoping user won't overflow the array with his choice how many numbers he wants to input. Don't forget to delete the allocated array at the end of your code and free the used memory.
#include <vector>
Now we can use vectors in our code. Let see some examples:
vector<int> first; //creates empty vector of integers
vector<int> second(100, 0); //creates vector with 100 zeroes
vector<float> third(3, 5.3); //creates vector, with three values 5.3
vector<int> fourth(second); //creates a copy of second vector
At first, we defined 4 vectors (see the explanations). The different ways of declaring a vector are called allocators.
vector<int> first; //creates empty vector of integers
//read until user writes 0
int read;
while(true) {
cin >> read;
if (read==0) break;
first.push_back(read);
};
cout << "You have written " << first.size() << " numbers.";
cout << "Last number was: " << first.back();
first.back()=10; //change the last number to 10
cout << "First number was: " << first.front();
first.front()=10; //change the first number to 10
cout << "Third element was: " << first[2];
cout << "Third element was: " << first.at(2);
first[2]=10; //Change third number to 10
first.at(2)=10; //Change third number to 10
What is the difference between [n] and .at(n)?
first.clear();
first.pop_back();
g++ code.cpp -O3
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (1)
Commented: