Why does this code output before even reading input? - c++

My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}

You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.

There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.

Related

Why I can not see output in cycle (C++ simple code)?

I would like to edit numbers in p2 according to the code in for cycle.
But If I try to write out actual number in p2, I donĀ“t see anything in output.
What could I change to see it?
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i; i >0; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}
As pointed out by Ilya, you need to change the condition in the for loop. Right now, at the beginning of the for loop, i = 0, so the for loop never starts. Change it to the following:
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}
Since you did not initialize the value of i it takes the random value that is stored in its location.
So just make i 0 and loop it through until 10.
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
return 0;
}
Because you didn't initialize the i variable, it takes a random number of type int, causing the loop to misbehave. You need to make i=0 for it to work correctly.
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i=0; i < sizeof(p1)/sizeof(p1[0]); i++){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
sizeof(p1)/sizeof(p1[0]) is count of array elements.

Why does this code timeout on using break but not when I exit using loop counter variable?

I saw some algorithm for a problem and rewrote it but I changed the fast_count_segment function's inner loop exit condition j=n1 to the break statement,the code timed out. Why does this happen?
The code runs fine otherwise but when I submit to the online grader, it shows code timeout, but as soon as I replace break with j=n1, it passes.
Shouldn't both be doing the same thing?
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> fast_count_segments(vector<pair<int,int>> &v, vector<int> points) {
vector<int> cnt(points.size());
int n1=v.size(),n2=points.size(),i,j,count;
for(i=0;i<n2;i++){
count=0;
for(j=0;j<n1;j++){
if(points[i]>=v[j].first && points[i]<=v[j].second)
count++;
else if(points[i]<v[j].first)
break; //j=n1; Changed this statement to break
}
cnt[i]=count;
}
return cnt;
}
int main() {
int n, m,a,b;
cin >> n >> m;
vector<pair<int,int>> v;
for (size_t i = 0; i < n; i++) {
cin >>a>>b;
v.push_back(make_pair(a,b));
}
vector<int> points(m);
for (size_t i = 0; i < points.size(); i++) {
cin >> points[i];
}
sort(v.begin(),v.end());
vector<int> cnt = fast_count_segments(v, points);
for (size_t i = 0; i < cnt.size(); i++) {
cout << cnt[i] << ' ';
}
cout<<endl;
return 0;
}

Segmentation fault in a program that reverses a dynamically allocated array

I was doing a test and the online test engine showing segmentation error, which is confusing because with no further details, and I checked the pointer no NULL and they work pretty fine, but don't how array here works. Because when debugging, everything is fine, until I try to cout/print out the array. it's reporting a is crushed here and break. I can do nothing here if it break, and I hit break or continue. if I continue, it runs just fine. so I was really confused.
My computer is windows 7, I run code in visual studio 2010 c++.
Debugging is not that clear to solve the problem, and I am learning c++ not very efficient.
Solve with Array need dynamic allocation.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int size, int num[]) {
if(size>1) {
int *p = &num[size-1];
int *f = num;
for(int i = 0;i < size/2; i++){
swap(*p, *f);
p--;
f++;
}
}
}
int main() {
int len;
int a[len];/This is the bug, can't use uninitialized var assign array/
cin >> len;
for(int i = 0; i < len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
return 0;
}
This has something to with dynamic allocation, when I work in java, I create a new array.
I have to
int[] newArray = {2,4,1,2,3};
or
int[] newArray = new int[] {2,4,1,2,3};
Finally, this problem is solved, which makes me very happy.
Reading and learning is very important, coding is also important.
Thanks all,
And using vector instead of using array.
It would be easier.
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int a;
int len;
vector<int> myvector;
cin >> len;
for(int i = 0; i < len; i++){
cin >> a;
myvector.push_back(a);
}
reverse(myvector.begin(), myvector.end());
for(int i = 0; i < len; i++){
cout << myvector[i] << " ";
}
return 0;
}
Using Array again(I doubt the following code):
#include<iostream>
//#include<cstdlib>
using namespace std;
void reverseArray(int size, int nums[]){
if(size > 1){
int *p = &nums[size-1];
int *q = nums;
for(int i = 0; i< size/2; i++){
swap(*p, *q);
p--;
q++;
}
}
}
int main(){
int len;
cin >> len;
int *a = new int[len];//a point to the first ele.
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
delete [] a;
return 0;
}
It worked perfect on my laptop, which is confusing because a is pointer, but I use it like an array. It shouldn't be working......
Final Array version:
http://ideone.com/ZMsD35
Done perfectly.
#include<iostream>
using namespace std;
int main(){
int len;
cin >> len;
int *a = new int[len];
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverse(a, a+len);
for(int i = 0; i< len; i++){
cout << a[i];
}
delete [] a;
system("pause");
return 0;
}
The most likely reason for a segfault is the input. When the testing software passes len of size sufficient to overflow the automatic storage area, your program crashes on this line:
int a[len];
The exact value of len is system-dependent, but an input of 1,000,000 should do it on most common systems.
The fix is really straightforward - replace the declaration with
int a* = new int[len];
This will place the data in dynamic memory, rather than the automatic memory. It will also make your program standard-compliant, because variable-length arrays in C++ are an extension to standards.
Don't forget to delete a once you are done to avoid memory leak:
delete[] a;

Size of a vector of pairs

I am filling up an adjacency list of vector with pairs given by :
vector<pair<int, int>> adj[1000];
I am doing a depth first search on the list but experiencing some weird behaviour. The first print statement prints some value which means I have some items in adj[s][0], adj[s][1], adj[s][2] and so on. However when I calculate the size of adj[s] in the next line it prints out to be zero. Am I missing something here?. Is my definition for vector of pairs correct?. The adjacency list is correctly filled because when I ran cout << adj[s][0].first << endl; in dfs, it was correctly showing me the neighbors of each and every node.
Complete code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <climits>
#include <algorithm>
using namespace std;
vector<pair<int, int>> adj[1000];
bool visited[1000];
int nodeweight[1000];
void initialize()
{
for(int i = 0; i < 1000; i++)
visited[i] = false;
for(int i=0; i < 1000; i++)
adj[i].clear();
for(int i = 0; i <1000; i++)
nodeweight[i] = INT_MAX;
}
void dfs(int s)
{
visited[s] = true;
cout << adj[s][1].first << endl;
int minimum = INT_MAX, tovisit = 0;
for(int i = 0; i < adj[s].size(); i++)
{
cout << adj[s][i].second;
if(!visited[adj[s][i].first] && adj[s][i].second < minimum)
{
minimum = adj[s][i].second;
tovisit = adj[s][i].first;
}
}
nodeweight[tovisit] = minimum;
//dfs(tovisit);
}
int main() {
int N, E;
cin >> N >> E;
while(E--)
{
int i, j, w;
cin >> i >> j >> w;
adj[i].push_back(make_pair(j,w));
adj[j].push_back(make_pair(i,w));
}
initialize();
for(int i = 1; i <= N; i++)
{
dfs(i);
}
return 0;
}
You are clearing adj again after filling in initialize().
First you fill adj in the while loop in main. Then you call initialize() which includes this loop clearing all vectors in it:
for(int i=0; i < 1000; i++)
adj[i].clear();
Then you have cout << adj[s][1].first << endl; in dfs which is undefined behavior because there are no elements in adj[s]. The fact that you seem to get the correct results is just coincidental undefined behavior (although practical it is because the memory holding the vector data was not cleared.)
adj[s].size() is correctly reported as 0.

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.
You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array