How to push an element into an array in C++? [duplicate] - c++

This question already has answers here:
C++ array (Beginner)
(4 answers)
PUSH an array C++?
(4 answers)
Closed 6 years ago.
I need to write a function that:
Goes through all numbers from 50 to 100
Checks what numbers are divisible by 6
Adds those numbers to an array
Writes that array
Writes how many elements there are in that array
I've searched for a function push in c++ but looks like there is none...
Got this far, doesnt wok...
int pushIntoArray(int array[], int size){
int index = 0;
int newArray[100];
for (int i=0; i<=size; i++){
if(array[i] % 6 == 0 && array[i] <= 100 && array[i] >= 50){
newArray[index] = array[i];
index++;
}
}
}

You can't. Arrays ir C++ (and C too) are fixed-size. And for a good reason too. They are a very low level concept, quite similar to a pointer. The memory for an array is allocated once, at the start, and doesn't change after that. An array is just a bunch of bytes in memory.
A "push" operation would require to change the size of the array, which would mean allocating new memory, copying the contents from the old one, and deleting the old memory. And that's the simple, non-optimized version.
So, no, an array cannot do this. However the standard library includes a std::vector class which does exactly that and more. That's the one you want.

As said in the comment, when the size of an arrays isn't fixed, use std::vector
And use tham like in the code below:
#include <iostream>
#include <vector>
std::vector<int> pushIntoVector(std::vector<int> values) {
std::vector<int> result; //A vector of integers
for (int a : values) // Goes through each values of the vector
if (a <= 100 && a >= 50 && !(a % 6)) {
std::cout << a << "\n";
result.push_back(a);
}
std::cout << result.size() << "\n";
return result;
}
int main()
{
std::vector<int> vec;
vec.push_back(36); //Not printed: < 50
vec.push_back(60); //Printed
vec.push_back(72); //Printed
vec.push_back(90); //Printed
vec.push_back(91); //Not printed: 91%6 != 0
vec.push_back(105); //Not printed: > 100
pushIntoVector(vec); //Do whatever you want with the returned vector
while (1);
return 0;
}

Related

Why is binary_search not working as expected? [duplicate]

This question already has answers here:
Can we use binary search with an unsorted array? [duplicate]
(3 answers)
What happens if a binary search on a non-sorted data set is attempted? [closed]
(4 answers)
Closed last year.
The question is to find the index of first element in the array that repeats itself atleast once in the array.
Input:
7
1 3 4 5 3 7 2
#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n], curr = -1;
int num = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
{
int x = a[i];
a[i] = -1;
if (binary_search(a, a + num, x))
{
curr = i;
cout << curr << endl;
break;
}
}
cout << curr + 1;
return 0;
}
Expected Output:
2
(As 3 is the first element to appear twice in the array)
Output received:
0
cin >> n;
int a[n]
This isn't allowed in C++. The size of an array variable must be compile time constant. n is not compile time constant. To create an array of runtime length, you must allocate it dynamically. Simplest solution is to use std::vector,
int num = sizeof(a) / sizeof(a[0]);
Use std::size(a) to get the size of an array instead. However, in this case, just use n.
binary_search(a, a + num, x)
The input range must be partially sorted in order to use std::binary_search with respect of the searched number. Since you use potentially all elements as the searched number, this effectively means that the array must be fully sorted.
Input:
7
1 3 4 5 3 7 2
Your input array is not fully sorted. As result of violating the pre-condition, the behaviour of the program is undefined.

Array doesn't print anything on executing code

I was creating a function that takes an integer number, finds the next multiple of 5 after the number and then if the difference between the multiple and the number is less than 3, then it prints out the multiple else the number itself, finally prints out an array of all the numbers.
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
vector<int> gradingStudents(vector<int> grades) {
int size=grades.size();
int c=0;
int d;
vector<int> array;
for(int i=0;i<size;i++){
while(grades[i]>(c*5)){
c++;
}
d=c*5;
if((d-grades[i])<3){
array[i]=d;
}else{
array[i]=grades[i];
}
d=0;
c=0;
}
return array ;
Now I tried running this function, and the compiler gives shows no error in the program in the code, however the code doesn't print anything.
Someone Please help.
First, I have to say that this code is extremely inefficient. Finding the difference between the closest muliplication of 5 and a number can be simply done by:
int difference = (n - (n + 4) / 5 * 5) - n;
Explanation: C++ is rounding down the division, so (n + 4) / 5 is n / 5 rounded up, and hence (n+4)/5*5 is the closest multiplication of 5.
Another thing, you declare an array but never resize it, so its size is 0. You need to resize it either by specifying the size in the constructor or using the std::vector::resize method.
code:
std::vector<int> gradingStudents(std::vector<int> grades) {
std::size_t size = grades.size();
std::vector<int> array(size);
for (int i = 0; i < size; i++) {
int closestMul = (grades[i] + 4) / 5 * 5;
if (closestMul - grades[i] < 3) {
array[i] = closestMul;
}
else {
array[i] = grades[i];
}
}
return array;
}
Proably your code is crashing, which is why it doesn't print anything. And one reason it might be crashing is your vector use is wrong.
It's very common to see beginners write code like this
vector<int> array;
for (int i=0;i<size;i++) {
array[i] = ...;
But your vector has zero size. So array[i] is an error, always.
Two possible solutions
1) Make the vector the correct size to begin with
vector<int> array(size);
for (int i=0;i<size;i++) {
array[i] = ...;
2) Use push_back to add items to the vector, every time you call push_back the vector increases in size by one.
vector<int> array(size);
for (int i=0;i<size;i++) {
array.push_back(...);
And please don't call your vector array, that's just taking the piss.
i feel nothing is wrong with your function but calling of this function is a bit tricky let me give you a quick main to try may be that will help you.
int main() {
vector <int> test ;
test.push_back(1);
test.push_back(2);
gradingStudents(test);
return 0;
}
Try initially the size of the vector is empty i hope you are sending something from the main . Your code is very inefficient whenever you find time must read how to write an efficient code.

Insert numbers divisible by a number into a vector

I was given the integers 15, 16, 17 ,18 ,19 and 20.
I am supposed to put only the numbers divisible by 4 into a vector and then display the values in the vector.
I know how to do the problem using arrays but I'm guessing I don't know how to properly use pushback or vectors.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> arrmain; int i,j;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
//output the elements in the vector
for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}
}
}
return 0;
}
wanted output: Numbers divisible by 4: 16, 20
As already mentioned in the comments, you have a couple of problems in your code.
All which will bite you in the end when writing more code.
A lot of them can be told to you by compiler-tools. For example by using -Weverything in clang.
To pick out the most important ones:
source.cpp:8:10: warning: declaration shadows a local variable [-Wshadow]
for (int i = 15; i <=20 ; i++)
and
source.cpp:6:26: warning: unused variable 'i' [-Wunused-variable]
vector arrmain; int i,j;
Beside those, you have a logical issue in your code:
for values to check
if value is ok
print all known correct values
This will result in: 16, 16, 20 when ran.
Instead, you want to change the scope of the printing so it doesn't print on every match.
Finally, the bug you are seeing:
for(j=0; j<=arrmain.size(); j++)
{
cout <<arrmain[i]<< " "<<endl;
}
This bug is the result of poor naming, let me rename so you see the problem:
for(innercounter=0; innercounter<=arrmain.size(); innercounter++)
{
cout <<arrmain[outercounter]<< " "<<endl;
}
Now, it should be clear that you are using the wrong variable to index the vector. This will be indexes 16 and 20, in a vector with max size of 2. As these indexes are out-of-bounds for the vector, you have undefined behavior. When using the right index, the <= also causes you to go 1 index out of the bounds of the vector use < instead.
Besides using better names for your variables, I would recommend using the range based for. This is available since C++11.
for (int value : arrmain)
{
cout << value << " "<<endl;
}
The main issues in your code are that you are (1) using the wrong variable to index your vector when printing its values, i.e. you use cout <<arrmain[i] instead of cout <<arrmain[j]; and (2) that you exceed array bounds when iterating up to j <= arrmain.size() (instead of j < arrmain.size(). Note that arrmain[arrmain.size()] exceeds the vector's bounds by one because vector indices are 0-based; an vector of size 5, for example, has valid indices ranging from 0..4, and 5 is out of bounds.
A minor issue is that you print the array's contents again and again while filling it up. You probably want to print it once after the first loop, not again and again within it.
int main()
{
vector<int> arrmain;
for (int i = 15; i <=20 ; i++)
{
//checking which numbers are divisible by 4
if (i%4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
}
}
//output the elements in the vector
for(int j=0; j<arrmain.size(); j++)
{
cout <<arrmain[j]<< " "<<endl;
}
return 0;
}
Concerning the range-based for loop mentioned in the comment, note that you can iterate over the elements of a vector using the following abbreviate syntax:
// could also be written as range-based for loop:
for(auto val : arrmain) {
cout << val << " "<<endl;
}
This syntax is called a range-based for loop and is described, for example, here at cppreference.com.
After running your code, I found two bugs which are fixed in code below.
vector<int> arrmain; int i, j;
for (int i = 15; i <= 20; i++)
{
//checking which numbers are divisible by 4
if (i % 4 == 0)
{ //if number is divisible by 4 inserting them into arrmain
arrmain.push_back(i);
//output the elements in the vector
for (j = 0; j < arrmain.size(); j++) // should be < instead of <=
{
cout << arrmain[j] << " " << endl; // j instead of i
}
}
}
This code will output: 16 16 20, as you are printing elements of vector after each insert operation. You can take second loop outside to avoid doing repeated operations.
Basically, vectors are used in case of handling dynamic size change. So you can use push_back() if you want to increase the size of the vector dynamically or you can use []operator if size is already predefined.

Inserting unique random numbers into a vector [duplicate]

This question already has answers here:
How to make Random Numbers unique
(6 answers)
Closed 6 years ago.
As a part of code for a certain game I want to generate 4 unique random numbers into a vector.
This code works for some number of repeated plays and then application crashes (not responding window).
While I understand that if-condition prevents for-loop from inserting the same number into a vector, how much time does this for-loop takes until it generates unique numbers via rand() function?
How srand(time(NULL)) and rand() exactly work together to create random values depending on the system time?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
//plays bulls and cows
int main() {
srand(time(NULL));
string play="yes";
int nums=4; // number of values in an answer (must NOT exceed 10)
vector<int> answer;
while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game
answer.push_back(rand()%10+1);
do { //fills vector with unique random numbers
for (int i=1; i<nums; i++) {
answer.push_back(rand()%10+1);
if (answer[i]==answer[i-1]) {
i=i-1;
continue;
}
}
} while (answer.size()!=nums);
for (int i=0; i<nums; i++) {
cout<<answer[i];
}
cout<<"Do you want to play again?"<<'\n';
cin>>play;
answer.clear();
} //game ends
if (play=="no" || play=="n" || play=="No" || play=="NO" || play=="N") { //terminates and checks for exceptions
cout<<"Thank you for playing!"<<'\n';
return 0;
} else {
cerr<<"Error: wrong input. Terminating."<<'\n';
return 0;
}
return 0; //safety return
}
Why do you add the new try into answer instead of temporary variable. If the variable is valid, then add it into the answer. In your case, i always keep at 1;
while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game
int last_try=rand()%10+1;
answer.push_back(last_try);
do { //fills vector with unique random numbers
int new_try=rand()%10+1;
if (last_try!=new_try)
{
answer.push_back(new_try);
last_try=new_try;
}
} while (answer.size()!=nums);
for (int i=0; i<nums; i++)
{
cout<<answer[i]<<"\n";
}
cout<<"Do you want to play again?"<<'\n';
cin>>play;
answer.clear();
} //game ends
Assume that you must use std::vector (and not a std::set). The easiest way to fill your vector with random numbers is to check to see if the number has already been "seen" -- if not, then add it to the vector.
This can be accomplished by using an array of bool as a helper to determine if the number has been seen:
#include <vector>
#include <iostream>
#include <cstdlib>
int main()
{
std::vector<int> answer;
int num = 4;
// 10 numbers
bool seen[10] = {false};
// keeps track of numbers added
int numsAdded = 0;
while (numsAdded < num)
{
int numRand = rand()%10;
if ( !seen[numRand] )
{
// not seen, so add it to vector and update bool array and
// numsAdded
answer.push_back(numRand + 1);
seen[num] = true;
++numsAdded;
}
}
for (size_t i = 0; i < num; ++i)
std::cout << answer[i] << " ";
}
Live Example
The problem is you always push back the random value in your vector before checking if it's valid. Let's say your program generates these random value in order:
2, 6, 6, 7, 9, 10
What happens is you will insert 2 (i == 2), 6 (i == 3), 6 (i == 4), then realize 6 is repeated twice, so you go back one iteration (i == 3), but both your sixes are still in your vector. So now you will add 7 (i == 4) and you will exit the for loop with 5 values in your vector.
Then when you evaluate your do-while condition, your answer.size() won't ever equal 4 because it already is equal to 5. You are now stuck in an infinite loop, and your application crashes when it consumes all the available memory from your vector growing infinitely.
Also, you appear to have an error in your logic. To make sure you don't have a repeated value (and you are stuck with vectors), you should not only validate the last inserted value but the whole vector. Like this:
#include <algorithm>
if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
do_this();
else
do that();

finding even numbers in the array issue (C++)

My code is to extract odd number and even number in an 1D array.
#include <iostream>
using namespace std;
int main() {
int a[6] = {1,6,3,8,5,10};
int odd[]={};
int even[]={};
for (int i=0; i < 6; i++) {
cin >> a[i];
}
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 1) {
odd[i] = a[i];
cout << odd[i] << endl;
}
}
cout << " " << endl;
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 0) {
even[i] = a[i];
cout << even[i] << endl;
}
}
return 0;
}
the output is:
1
3
5
2
1
6
It shows that it successfully extract odd numbers but the same method applied to the even number. It comes with an issue while the even number is 4.
Could anyone help me find the cause here? Thanks.
You've got an Undefined Behavior, so result may be any, even random, even formatted hard drive.
int odd[] = {} is the same as int odd[/*count of elements inside {}*/] = {/*nothing*/}, so it's int odd[0];
Result is not defined when you're accessing elements besides the end of array.
You probably have to think about correct odd/even arrays size, or use another auto-sizeable data structure.
First, although not causing a problem, you initialize an array with data and then overwrite it. The code
int a[6] = {1,6,3,8,5,10};
can be replaced with
int a[6];
Also, as stated in the comments,
int odd[]={};
isn't valid. You should either allocate a buffer as big as the main buffer (6 ints) or use a vector (although I personally prefer c-style arrays for small sizes, because they avoid heap allocations and extra complexity). With the full-size buffer technique, you need a value like -1 (assuming you intend to only input positive numbers) to store after the list of values in the arrays to tell your output code to stop reading, or store the sizes somewhere. This is to prevent reading values that haven't been set.
I don't understand your problem when 4 is in the input. Your code looks fine except for your arrays.
You can use std::vector< int > odd; and then call only odd.push_back(elem) whem elem is odd.