The vector of random integers cannot be printed, C++ - c++

I wrote a simple program to generate a vector of random numbers. I tried to print each element in the vector but the output doesn't seem correct. For example, I push_back 5 numbers but the vector.size() gives 10... I have no idea why. Please help.
#include <iostream>
#include <vector>
#include <time.h>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
vector<int> arr(5);
int i, val;
for (i=0; i<5; i++)
{
val = rand()%30;
cout << "value " << i << " is " << val << endl;
arr.push_back(val);
}
for (i=0; i<arr.size() ; i++){
cout << arr[i] << " " << arr.size() << endl;
}
return 0;
}
OUTPUT:
value 0 is 2
value 1 is 13
value 2 is 9
value 3 is 28
value 4 is 27
0 10
0 10
0 10
0 10
0 10
2 10
13 10
9 10
28 10
27 10

In line
vector<int> arr(5);
you already allocated 5 entries. You can access them without pushing back new elements. eg:
vector<int> arr(5);
arr[1];
is valid and won't crash.
Now if you do additional push_back you will extend existing vector, so it will change its size.

vector<int> arr(5);
This creates a vector of 5 elements.
arr.push_back(val);
This appends one new element to the vector. So the first time it is called, the vector will now contain 6 elements.

The vector constructor you are using, creates a vector with 5 values (equal to 0) already present in it. If you want to make the vector allocate space for 5 elements (as I am assuming - your plan). You can create a vector with a default constructor and then use the reserve method.

instead of
vector<int> arr(5);
It should read
vector<int> arr;
arr.reserve(5);

Related

Truncate the last few elements of an array

I am new to C and C++, please help me in getting the required solution. I have used memcpy to copy the contents of 'array' to 'arr'. But since the size of 'arr' is 10, it appends 0 to the remaining elements. How can I truncate the 'arr' to size 5.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
uint8_t array[5] = {1,2,3,4,5};
uint8_t arr[10] = {0};
memcpy( arr, array, 5);
for (auto e: arr){
cout << e << " ";
}
return 0;
}
Output for the above code: 1 2 3 4 5 0 0 0 0 0
required output : 1 2 3 4 5
You cannot truncate the size of the static array after compilation. If you were using some other data structure like vector from C++ STL then the size of that container object might have been variable.
Instead of
for (auto e: arr){
cout << e << " ";
}
you can keep array's size in a variable and cout arr that times, like:
int i, arraySize = 5;
for (i=0; i<arraySize; i++) {
cout << arr[i] << " ";
}
Best Practice is to create a pointer and free the memory or second way is to don't allow kernel to give memory to you create custom memory allocator and assign it to your array

I wanted to reverse my array. Why this code gives garbage value?

#include <iostream>
using namespace std;
int main(){
int n;
int a[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
}
Input:- 4
1 2 3 4
Output 4199008 4 3 2 1
For starters the program has undefined behavior because the variable n is not initialized
int n;
So this declaration
int a[n];
is invalid. Moreover variable length arrays is not a standard C++ feature. Instead use the standard class template std::vector.
Also within this loop
for(int i=n;i>=0;i--) {
cout<<a[i]<<" ";
}
you are trying to access of non-existent element with the index n.
Also you are not reversing an array. You are trying to output an array in the reverse order.
Pay attention to that there are standard algorithms std::reverse and std::reverse_copy declared in the header <algorithm>.
Here is an example how your program with using your approach could look
#include <iostream>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
for ( auto &item : v ) std::cin >> item;
std::cout << "The array in the reverse order\n";
for ( size_t i = v.size(); i != 0; )
{
std::cout << v[--i] << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look like
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
If to use standard algorithms then your program can look the following way
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
std::copy_n( std::istream_iterator<int>( std::cin ), n, std::begin( v ) );
std::cout << "The array in the reverse order\n";
std::reverse_copy( std::begin( v ), std::end( v ),
std::ostream_iterator<int>( std::cout, " ") );
std::cout << '\n';
return 0;
}
The program output might look the same way as shown above
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
a[n] will return the element after the last one. When you iterate in reverse order, start with i=n-1.
At the beginig of your program there is a mistake:
int n; // You declare n with no value
int a[n]; // You use is
cin>>n; // After you used it you get your value-
Now i can suppose that that was just an error while copying it because you give inputs and outputs
Input:- 4 1 2 3 4 Output 4199008 4 3 2 1
So forgeting about that, you declare an array of size n. Remember that the elemnts of the array will go from 0 to n-1. Now look at your second for loop
// the first element you acces is n and you stop at 1
// but the array goes from n-1 to 0
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
So you still get n values as an output but the first element that you access is outside of the array. Thats why you get a garbage value, that is a value that was left there.
A solution will be to change the for loop
for(int i=n-1;i>=-1;i--){
cout<<a[i]<<" ";
}
While reversing the array start the loop from n-1 that is i=n-1 (n is the no of elements in array). And run the loop till i>=0. If you will start loop from n it will read illegal index which is out of range and will give you garbage value.
for(int i=n-1; i>=0; i++){
cout<<arr[i]<<" ";}

std::sort() function not able to sort a part of a vector

The std::sort function is somehow not able to sort a particular part of a vector. The upper bound and lower bound of the part of the vector to be sorted are entered as inputs along with size of vector and vector elements. This is what I've tried:
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
int main()
{
long long int N,L,R;
cin>>N;
vector <long long int> V;
while(N--)
{
long long int input;
cin>>input;
V.push_back(input);
}
cin>>L>>R;
sort(V.begin()+L-1,V.begin()+R-1);
vector<long long int>::iterator I = V.begin();
while(I<V.end())
{
cout << *I << " ";
I++;
}
cout << endl;
}
My input:
5
3 -1 4 2 -1
3 4
Expected output:
3 -1 2 4 -1
Actual output:
3 -1 4 2 -1 (unchanged)
Kindly tell what is incorrect in this approach/ what other method can be applied.
The second parameter (last) is pointing one past the last element that should be sorted. So when the iterators you pass to sort are
3 -1 4 2 -1
^-------- first
^------ last
Then there is only a single element in the range to be sorted and the output you get is to be expected.

long integer multiplication in c++

I am a beginner in C++. I am trying this long integer multiplication. I am not understanding that how the value ofsum[3][0] is changing in the subsequent loop cycle.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num1, num2;
int i,j,l1, l2,temp,k;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
l1= num1.size();
l2= num2.size();
cout << l1 << " " << l2 << endl;
int sum[l2-1][l2]; // 5 6 7 8 ---> num1
// 1 2 3 4 ---> num2
for(i=0; i<l1; i++) // ---------
num1[i]-='0'; // 2 2 7 1 2 sum[3][4]---->sum[3][0]
// 1 7 0 3 4 i.e sum[3][0] should be 2
for(i=0; i<l2; i++) // 1 1 3 5 6
num2[i]-='0'; // 5 6 7 8
// -------------
for(i=l2-1; i>=0; i--) // 7 0 0 6 6 5 2
{
k=0;
temp=0;
for(j=l1-1; j>=0; j--)
{
temp+=(num2[i]*num1[j]);
sum[i][k]= temp%10;
temp=temp/10;
k++;
}
sum[i][k]=temp;
cout << sum[3][0] << endl;
}
for(i=l2-1; i>=0; i--) // output is 2 2 7 1 1 Here value of sum[3][0] is 1 but the desired output is 2.
{ // 1 7 0 3 1
for(k=l2; k>=0; k--) // 1 1 3 5 0
cout << sum[i][k]; // 0 5 6 7 8
cout << endl;
}
return 0;
}
I tried this code for the case num1=5678 and num2=1234. So sum[3][0] should be 2 in that case.
You did not make sum large enough. You use sum[0..l2-1][0..l1] so the size would need to be sum[l2][l1+1].
When you exceed the second dim of sum that typically makes part of one row of sum share storage with part of another, so the place where you stored sum[2][0] is the same place you later stored sum[1][4]
When you exceed the first dim of sum (or the second dim in the last row) that makes sum share storage with other things, such as(but not necessarily) the other variables local to that function.
Also, your loop for displaying sum is incorrect. You use rows of sum from l2-1 down to 0 and columns from 0 up to L1. But you display columns l2 down to 0. The columns are computed based on l1, so should be displayed based on l1. That error would have symptoms if you tried an example with l1 not equal l2.
The sum array should be create like this:
int sum[l2][max(l1,l2)+1];
It is too small to store results of you calculations now.
Why program doesn't crash while you write out of bounds of the array? Because C++ has not any array bounds checking.
To be honest, you should declare the array by new and remove it by delete when it is not needed anymore. C++ standard doesn't provide to create non-constant size array without new. Only some compilers supports it as an extension and many of them prints warnings when you do that. More informations here: How do I declare a 2d array in C++ using new?

How do I add elements to an empty vector in a loop?

I am trying to create an empty vector inside a loop, and want to add an element to the vector each time something is read in to that loop.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<float> myVector();
float x;
while(cin >> x)
myVector.insert(x);
return 0;
}
But this is giving me error messages.
You need to use std::vector::push_back() instead:
while(cin >> x)
myVector.push_back(x);
// ^^^^^^^^^
and not std::vector::insert(), which, as you can see in the link, needs an iterator to indicate the position where you want to insert the element.
Also, as what #Joel has commented, you should remove the parentheses in your vector variable's definition.
std::vector<float> myVector;
and not
std::vector<float> myVector();
By doing the latter, you run into C++'s Most Vexing Parse problem.
Use push_back:
while(cin >> x)
myVector.push_back(x);
The insert function takes an iterator as the first argument, indicating the position to insert.
Also, you need to get rid of the parentheses in the declaration of myVector:
std::vector<float> myVector;
If you want to use myVector.insert(),
use it like myVector.insert(myVector.end(), x). This will append x at the end of myVector.
You can insert x in the beginning by myVector.insert(myVector.begin(), x).
Another option is to use std::vector::emplace_back() instead of std::vector::push_back(). The makes some optimizations and doesn't take an argument of type vector::value_type, it takes variadic arguments that are forwarded to the constructor of the appended item, while push_back can make unnecessary copies or movements.
This is demonstrated in the std::vector::emplace_back documentation and here is a related question.
Usage example:
std::vector<int> myVector;
while (cin >> x) {
myVector.emplace_back(x);
}
The code below may answer your question and also brings some other examples regarding how to insert new elements in different position or index.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vector_of_integers{};
vector_of_integers.push_back(1); // O(1)
vector_of_integers.push_back(3); // O(1)
vector_of_integers.push_back(5); // O(1)
vector_of_integers.push_back(7); // O(1)
for (int i = 8; i <= 10; i++)
vector_of_integers.push_back(i);
// Printing out all the elements of vector of integers - Method 1
copy(vector_of_integers.begin(), vector_of_integers.end(), ostream_iterator<int>(cout, " ")); // 1 3 5 7 8 9 10
cout << endl << endl;
// Inserting '2' at index 1
vector<int>::iterator it{ vector_of_integers.begin() };
advance(it, 1);
vector_of_integers.insert(it, 2); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 2
for (auto const& element : vector_of_integers)
std::cout << element << " "; // 1 2 3 5 7 8 9 10
cout << endl << endl;
// "it" no longer valid, get a new one
it = vector_of_integers.begin();
vector_of_integers.insert(it + 4, 6); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 3
for (it = vector_of_integers.begin(); it != vector_of_integers.end(); it++)
std::cout << *it << ' '; // 1 2 3 5 6 7 8 9 10
cout << endl << endl;
// insert '4' 7 times at index 3
vector<int> new_vector_to_be_inserted(7, 4);
vector_of_integers.insert(vector_of_integers.begin() + 3, new_vector_to_be_inserted.begin(), new_vector_to_be_inserted.end()); // O(N+M) => M is size of elements to be inserted
// Printing out all the elements of vector of integers - Method 4
for (int i = 0; i < vector_of_integers.size(); i++)
cout << vector_of_integers.at(i) << ' '; // 1 2 3 4 4 4 4 4 4 4 5 6 7 8 9 10
cout << endl << endl;
return 0;
}