I created this program:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> m(n);
for(int i=0;i<n;i++){
cin>>m[i];
}
sort(m.begin(),m.end());
vector<bool> used(n,false);
for(int i=n;i>0;i--){
for(int j=i;j>0;j--){
if((m[i]/m[j]>=2)&&(used[i]==false))
used[j]=true;
}
}
int numOfElem=0;
for(int i=0;i<n;i++){
if(used[i]!=true){
numOfElem++;
}
}
cout<<"\n"<<numOfElem<<"\n";
return 0;
}
Now for some reason right after I input elements of vector m I get command terminated, does anyone know the cause of this problem?
You access the vectors m and used out of bounds since you start iterating with i == n (the size of the vectors). This causes your program to have undefined behavior and a crash is one possible outcome of that.
Suggested fix:
for(int i = n - 1; i >= 0; i--) { // start with n-1 and ...
for(int j = i; j >= 0; j--) { // ... include 0 in the loop
Also note that m[i] / m[j] may be a division by zero and throw an exception, so you may want to check if m[j] == 0 before doing the division too.
Related
I was working on a problem statement. For its implementation, I am using vectors.
#include <iostream>
#include <vector>
using namespace std;
int busRemaining(vector<vector<int>> &busStation) {
int answer=0;
for(int i=0; i<=busStation.size(); i++) {
for(int j=i+1; j<=busStation.size(); j++)
{
if((busStation[i][0] <= busStation[j][0]) && (busStation[i][1] >= busStation[j][0])) {
answer++;
}
}
}
return answer;
}
int main()
{
vector<vector<int>> v = {{2, 8},{6, 10},{12, 14},{12, 20}};
cout<<busRemaining(v);
return 0;
}
The issue I am facing is -> after I run the program nothing is printed on the console. I have initialized answer to 0, So I suggest even if my looping logic is wrong it should return 0 at least.
You are using the wrong condition for your for-loops. Vector's are zero-indexed, so you should use less-than instead of less-than-or-equal:
for (int i = 0; i < busStation.size(); i++)
^
|
here
and
for (int j = i + 1; j < busStation.size(); j++)
^
|
here
The reason your function does not return, is because you touch memory outside the vector, memory that might not be allocated by your program, which makes your program's behavior undefined, i.e. the behavior of your program depends on the compiler and the operating system you use.
I could problems in your code, you can not access busStation[busStation.size()] because that element does not exist. Try to fix that issue first.
As you can see, in both for loops you have put i<=busStation.size(); and j<=busStation.size();. It is giving out of range error and causing a runtime error. it should be < and not <=. I hope you know why is it so. And in the 2nd loop, you have used again busStation.size() which might cause an error if you are trying to iterate elements of individual vectors inside vectors. I have written this code just to fix errors. I don't know if it works as you want.
#include <iostream>
#include <vector>
using namespace std;
int busRemaining(vector<vector<int>> &busStation) {
int answer=0;
for(int i=0; i<busStation.size(); i++) {
for(int j=i+1; j<busStation[i].size(); j++)
{
if((busStation[i][0] <= busStation[j][0]) && (busStation[i][1] >= busStation[j][0])) {
answer++;
}
}
}
return answer;
}
int main()
{
vector<vector<int>> v = {{2, 8},{6, 10},{12, 14},{12, 20}};
cout<<busRemaining(v);
return 0;
}
I'm having trouble with a C6385 warning in my code. I'm trying to see if two arrays will equal each other. The warning I keep getting is on the line where if(p[i] == inputGuess[j]). I have tried redoing these line but I keep getting the same warning. Does anyone know what I'm doing wrong. This is also my first time programming in C++.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
int* generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cout << numbers[i]<< " " << endl;
}
return numbers;
}
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; i < n; j++) {
if (p[i] == inputGuess[j]){ //Where I keep getting the C6385 Warning
sum++;
break;
}
}
}
}
The C6385 warning documentation states:
The readable extent of the buffer might be smaller than the index used
to read from it. Attempts to read data outside the valid range leads
to buffer overrun.
https://learn.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160
Your second if statement compares i < n instead of j < n and since i is never modified inside it will run forever. This causes the warning since you’ll access memory out of bounds. Fix the comparison.
I have tried to do some practice with vector, and I made a simple for loop to calculate the sum of the elements within the vector. The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for loop altogether, and I have not come up with a reasonable explanation.
//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;
int simplefunction(vector<int>vect)
{
int size = vect.size();
int sum = 0;
for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
{
sum = sum + vect[count];
}
return sum; //<<---the return sum is 0
}
int main()
{
vector<int>myvector(10);
for (int i = 0; i == 10; i++)
{
myvector.push_back(i);
}
int sum = simplefunction(myvector);
cout << "the result of the sum is " << sum;
return 0;
}
I have done some research, and usually the ill-defined for loop shows up when the final condition cannot be met (Ex: when setting count-- instead of count++)
Your loop's conditions are wrong, as they are always false!
Look at to the loops there
for (int i = 0; i == 10; i++)
// ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
and
for (int count=0; count==4; count++)
// ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
you are checking i is equal to 10 and 4 respectively, before incrementing it. That is always false. Hence it has not executed further. They should be
for (int i = 0; i < 10; i++) and for (int count=0; count<4; count++)
Secondly, vector<int> myvector(10); allocates a vector of integers and initialized with 0 s. Meaning, the loop afterwards this line (i.e. in the main())
for (int i = 0; i == 10; i++) {
myvector.push_back(i);
}
will insert 10 more elements (i.e. i s) to it, and you will end up with myvector with 20 elements. You probably meant to do
std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++)
{
myvector.push_back(i);
}
or simpler using std::iota from <numeric> header.
#include <numeric> // std::iota
std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);
As a side note, avoid practising with using namespace std;
So the prompt I was given was "Write a function that is given an array of ints and returns the sum of the even numbers in the array. The function is not given the length of array, but the last number in the array is -1. For example, if the array contains {2,3,5,4,-1} the function returns 6. Use the header int sumEven(int myArray[]). "
and the code I've written so far is
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; i++;){
if (myArray[i] >=0) {
sum+=myArray[i];
}
}
return sum;
}
But it keeps returning back zero's? I'm not seeing what I'm doing wrong here
The typical order of parameters to a for() loop are like so:
for(<initialize variable>; <end condition>; <increment variable>)
In your example, you have the i++ as your second parameter to the for loop, which is incorrect. It will return 0 (since i starts as 0, and i++ is post-increment, so it returns 0 and then increments to 1) and your for loop will exit immediately, since 0 evaluates to false.
Instead, replace the end condition with the end condition you've described: myArray[i] != -1. You should also include a check to see if the number is even before adding it to sum, which can be done by checking to see if the remainder when divided by 2 is 0.
#include <iostream>
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; myArray[i] != -1; i++){
if(myArray[i] % 2 == 0)
sum += myArray[i];
}
return sum;
}
The error is in the for loop. You should change the for loop to for (int i=0; ; i++) and you should also add a break statement to exit the for loop.
using namespace std;
int sumEven(int myArray[]){
int sum = 0;
for (int i=0; ; i++){
if (myArray[i] >=0) {
sum+=myArray[i];
}
else
{
break;
}
}
return sum;
}
int sumEven(int arr[]) {
int sum = 0;
// int len = (sizeof(arr)/sizeof(*arr)); // Since this will not work for all cases.
// auto len = end(arr) - begin(arr);
for (int i = 0; arr[i] >= 0; i++) {
if(arr[i]%2==0)
sum += arr[i];
}
return sum;
}
i guess the
for (int i=0; i++;){
make no iterations, cause condition to continue loop is "i++" - which is initialy zero.
Replace it with following for example
for (int i=0; i < array_length; i++;){
I am trying to write a program that takes an input of of n integers, and finds out the one that occurs the maximum number of times in the given input. I am trying to run the program for t cases.
For this, I have implemented a counting sort like algorithm (perhaps a bit naiive), that counts the number of occurrences of each number in the input. In case there are multiple numbers with the same maximum occurrence, I need to return the smaller among those. For this, I implemented sorting.
The issue I am facing is, that every time I run the program on Visual C++, I am getting an error that tells "vector subscript out of range". Under Netbeans, it is generating a return value of 1 and exiting. Please help me find the problem
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findmax(vector<int> a, int n)
{
int i,ret;
ret = 0;
for ( i = 0; i <n; i++)
{
if (a[i] > ret) {
ret = a[i];
}
}
return ret;
}
int main() {
int i = 0, j = 0, k = 0, n,m,r1,r2;
vector<int> a;
int t;
vector<int> buff;
cin>>t;
while(t--) {
cin>>n;
a.clear();
buff.clear();
for ( i = 0; i < n; i++) {
cin>>a[i];
}
sort(a.begin(),a.end());
m = findmax(a,n);
for ( j = 0; j < m+1; j++) {
buff[a[j]] = buff[a[j]] + 1;
}
k = findmax(buff,m+1);
for ( i = 0; i < m+1; i++) {
if (buff[i] == k) {
r1 = i;
r2 = buff[i];
break;
}
}
cout<<r1<<" "<<r2<<endl;
}
return 0;
}
After a.clear() the vector doesn't have any members, and its size is 0.
Add a call to a.resize(n) to make it the proper size. You also need to resize buff to whatever size it needs to be.
this line it's the culprit:
cin>>a[i];
you must use push_back:
cin >> temp;
a.push_back(temp);
or resize(n) before:
cin>>n;
a.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
then you should pass you vector by reference to findmax
int findmax(vector<int> &a, int n)
...
This isn't how you populate an array.
cin>>a[i];
You need to use the push_back() method or pre-allocate the appropriate size.
The problem is that you're illegally using indexes of your vector that don't exist (you never add any items to the vector). Since you know the size, you can resize it after you clear it:
a.clear();
a.resize(n);
buff.clear();
buff.resize(n);
for ( i = 0; i < n; i++) {
cin>>a[i];
}
will be out of range. The vector, as you construct it, has zero size.