Output not coming as expected for function call inside loop - c++

#include <iostream>
#include <vector>
#include <set>
#include <list>
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <memory>
#include "C:\Users\HP\Documents\Dreyfus-Wagner\Dijkstra.h"
using namespace std;
#define MAX 100001
#define pir pair<int, int>
#define pbd(x) push_back(x)
using namespace std;
#define MAX 100001
#define pir pair<int, int>
#define pbd(x) push_back(x)
struct Out
{
int *p;
};
vector<pir> Graph[MAX];
int main()
{
int nodes1, edges1, starting1;
// create graph
cout << "Enter the number of vertices and edges: ";
cin >> nodes1 >> edges1;
cout << "Enter the edges with weigth: <source> <destination> <weigth>: \n";
int u1, v1, w1;
struct Out output[nodes1];
int adjMatrix[nodes1][nodes1];
for (int i = 0; i < edges1; i++)
{
cin >> u1 >> v1 >> w1;
Graph[u1].pbd(pir(v1, w1));
Graph[v1].pbd(pir(u1, w1)); // for undirected
}
cout << "Enter the source node: ";
cin >> starting1;
for (int i = 1; i <= nodes1; i++)
{
output[i].p = Djiktra(nodes1, edges1, i, Graph);
}
for (int j = 1; j <= nodes1; j++)
{
for (int i = 1; i <= nodes1; i++)
{
cout << "*(p + " << i << ") : ";
cout << *(output[j].p + i) << endl;
;
}
cout << " " << endl;
}
}
If we call the single instance of function it gives correct output.
Note : Djiktra function is stored in another file that is referred in header. The idea is that to find shortest lengths of elements per node
Could anyone explain why the output is incorrect when called inside for loop?

Related

Given an array of integers, find the sum of its elements. where is the error?

For some reason I am not getting the desired answer and I can't fathom where the error is.
For example, given the array ar = [1,2,3], 1+2+3 = 6, so return 6, but I am getting 650462183 instead.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arr\n";
cin >> arr[i];
int count = 0;
for (int j = 0; j <= i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
The array int arr[i]; has only i elements: arr[0] to arr[i-1].
Therefore, the condition of the loop should be j < i, not j <= i.
cin >> arr[i]; is also wrong. You should use another loop to read i elements instead of readling only one to an out-of-range element like this.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arr\n";
for (int j = 0; j < i; j++)
{
cin >> arr[j];
}
int count = 0;
for (int j = 0; j < i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
Note that variable-length arrays (VLA) like int arr[i]; is not supported in the standard C++. You should use std::vector instead. You can do this by changing int arr[i]; to std::vector<int> arr(i); in this case.
Another choice is not using arrays and summing what are entered directly:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
cout << "enter the value of yout arr\n";
int count = 0;
for (int j = 0; j < i; j++)
{
int element;
cin >> element;
count += element;
}
cout << count << endl;
return 0;
}

Fill up a vector with input from a user

I am learning c++ and i have a problem with filling a vector with the input from the user. wWenever i try to run my code, a window pops-up with 'vector subscript out of range' written in it.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int s(0), values(0);
vector <int> grades;
cout << "Enter the number of grades you want to enter: \n";
cin >> s;
cout << "Enter the values:";
for (int i(0); i < s; i++)
{
cin >> values;
grades.push_back(values);
}
int grades_size(grades.size());
int average(0);
for (int m(0); m <= grades_size; m++)
{
average += grades[m];
}
average /= grades_size;
cout << "Your average is" << average;
return 0;
}
You can read things from input using streams.
The following example shows how to use the succinct syntax of ranges to do that:
#include <iostream>
#include <range/v3/view/istream.hpp>
#include <range/v3/range/conversion.hpp>
int main()
{
auto vec = ranges::istream<int>(std::cin) | ranges::to_vector;
for (auto elem : vec) {
std::cout << elem << std::endl;
}
}

c++ variable sized arrays from Hackerrank with vectors

I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.
My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}
This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}

Tic Tac Toe array wrong characters

The screenshot says it all, the characters i use are correctly put inside the array. However, some other random characters are inserted in the array as well. I'm confused!
main.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char gameBoard [3][3];
cout << "**** Welcome to Leviathan's first TicTacToe Game! ****\n\n";
Players playersObject;
playersObject.getPlayersNames();
playersObject.printPlayersNames();
GameLayout gameObject;
gameObject.printLayout();
Game gamestartObject;
gamestartObject.gameStart(gameBoard);
}
game.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Game::gameStart(char board[3][3])
{
char player1char,player2char;
size_t i,j;
cout << "Enter player 1 character :";
cin >> player1char;
cout << "Enter player 2 character :";
cin >> player2char;
int row,column;
bool isDone = false;
while(isDone == false)
{
cout << "Player 1->choose row";
cin >> row;
cout << "Player 1->choose column";
cin >> column;
board[row-1][column-1] = player1char;
cout << "Player 2->choose row";
cin >> row;
cout << "Player 2->choose column";
cin >> column;
board[row-1][column-1] = player2char;
GameLayout layout;
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
}
Players.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void Players::getPlayersNames()
{
string p1,p2;
cout << "Enter player 1 name : ";
cin >> p1;
cout << "\nEnter player 2 name : ";
cin >> p2;
_player1Name = p1;
_player2Name = p2;
}
void Players::printPlayersNames()
{
cout << "Alright " << _player1Name << " and " << _player2Name <<", the game has begun!\n\n";
}
GameLayout.cpp :
#include "Players.h"
#include "GameLayout.h"
#include "Game.h"
#include <iostream>
#include <string>
using namespace std;
void GameLayout::printLayout()
{
size_t i,j;
char board[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
board[i][j] = '.';
}
}
cout << " |1||2||3|" <<endl;
for(i=0; i<3; i++)
{
cout << i+1 << "|";
for(j=0; j<3; j++)
{
cout <<" "<<board[i][j] << " " ;
}
cout << endl;
}
}
Game.h :
#ifndef GAME_H
#define GAME_H
class Game
{
public:
void gameStart(char board[3][3]);
private:
};
#endif // GAME_H
GameLayout :
#ifndef GAMELAYOUT_H
#define GAMELAYOUT_H
class GameLayout
{
public:
void printLayout();
private:
};
#endif // GAMELAYOUT_H
Players.h :
#ifndef PLAYERS_H
#define PLAYERS_H
#include <string>
class Players
{
public:
void getPlayersNames();
void printPlayersNames();
private:
std::string _player1Name;
std::string _player2Name;
};
#endif // PLAYERS_H
Local non-static variables in a function, like e.g. gameBoard, are not initialized. You need to explicitly initialize it, or its contents will be indeterminate and reading its values will lead to undefined behavior.
You can simply do it like
char gameBoard [3][3] = { ' ' };

C++ input loop gives "Process finished with exit code 11" Error

The following is the start of my C++ code. I'd like to be able to type in 5 inputs and get them stored in the vector. However the code breaks on the double array element access. How can I fix this and why is it breaking? The error I'm getting on my IDE (CLion) is "could not find operator[]".
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;
int main () {
vector<int> inputVec;
int x;
while (cin >> x && inputVec.size() < 5) {
inputVec.push_back(x);
cout << inputVec.size() << endl;
}
sort(inputVec.begin(), inputVec.end());
cout << "before if 1" << endl;
typedef vector<double>::size_type vec_sz;
vec_sz size = inputVec.size();
cout << "before if 3" << endl;
if (size < 4) {
cout << "too few inputs";
} else {
cout << "calculating quartiles" << endl;
int quartileSize = size / 4;
int leftOvers = size - quartileSize * 4;
int count = 0;
vector<vector<int>> quartiles(4);
for (int i = 0; i < 3; i++) {
for (int j = 0; i < quartileSize; j++) {
quartiles[i][j] = inputVec[count++];
}
}