Fill up a vector with input from a user - c++

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;
}
}

Related

Copy part of a matrix and paste on another one C++

The user input a matrix, and the output must be a new matrix with an additional column of zeros. If we apply the script to a 2 square matrix like : {1,2,3,4} the new matrix output will be a 2 rows & 3 columns : {1,2,32,3,4,0}. I don't understand the number 32 output.
#include <iostream>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
int A[m][n]={};
int M[m][n+1]={0};
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
Variable length arrays (VLAs) are a non-portable gcc extension and evidently don't initialise as you would expect.
One solution is to use std::vector instead which is portable and will do what you want, something like this:
#include <iostream>
#include <vector>
int main(){
int m,n;
std::cout << "Input the size of the square matrix : ";
std::cin >> m;
n=m;
std::vector <std::vector <int>> A;
std::vector <std::vector <int>> M;
A.resize (m);
M.resize (m);
for (int i = 0; i < m; ++i)
{
A [i].resize (n);
M [i].resize (n + 1);
}
for (int i(0);i<m;i++){
for(int j(0);j<n;j++){
std::cout << "Input element A["<<i<<"]["<<j<<"] : ";
std::cin >> A[i][j];
M[i][j]=A[i][j];
std::cout << "\n";
}
}
for (int i(0);i<m;i++){
for(int j(0);j<=n;j++){
std::cout << M[i][j] << " ";
}
std::cout << "\n";
}
}
Live demo
In the bad old days of C, you could realloc() the array bigger and memset() the new column (only good for the last dimension, where items are adjacent).

How can I input data to array and print them through function?

I am trying to input data to an array and then print them by using a function but I am not sure how to organize the code.
#include <iostream>
using namespace std;
void showGrade(double grade[], int size);
int main()
{
double grade[];
int size;
for (int i = 0; i < size; i++)
{
cout << "Please enter the number of grade" << endl;
cin >> size;
}
showGrade(grade, size);
return 0;
}
void showGrade(double grade[], int size) //How many grade we have
{
for (int counter = 0; counter < size; counter++)
{
cout << "Please enter your grades: " << endl;
cin >> grade[counter];
cout << "Here are your grades: " << endl;
}
}
I Expect to see how many grades I input and then show them.
UPDATE 8/28/19
I figured out how to do it in main function successfully. But what I really want is to put them in a seperate function. My new codes have error at the function call which is type name is not allowed and expected a ')'. How do I make it work?
#include <iostream>
using namespace std;
void showGrades(double ar[], int size);
int main()
{
double ar[20];
int size;
showGrades(double ar[size], int size);
system("pause");
return 0;
}
void showGrades(double ar[], int size) {
cout << "Please enter the number of grade "; // array size
cin >> size;
cout << "Please enter your grades " << endl;
for (int i = 0; i < size; i++) {
cin >> ar[i];
}
cout << "The grades you entered are: " << endl;
for (int i = 0; i < size; i++) {
cout << ar[i] << endl;
}
}
First of all, you need to use the standard container
std::vector
instead of the double grade[];, since you want a variable-length
array as per user input.
Secondly, you are using un-initialized size variable in
for (int i = 0; i < size; i++)
hence it will be initialized with a garbage value. There you need no for-loop
A good starting would be:
#include <iostream>
#include <vector> // std::vector
void showGrade(std::vector<double>& grade)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
// the logic
}
int main()
{
int size;
std::cout << "Please enter the number of grade" << endl;
std::cin >> size;
std::vector<double> grade;
grade.reserve(size); // reserve memory for unwanted re-allocations
showGrade(grade);
return 0;
}
I leave it to you to complete, after reading about the std::vector more.
Also, do not practice with using namespace std;. Read more:
Why is "using namespace std;" considered bad practice?
this is not a valid C++ code:
double grade[];
You can use std::vector:
std::vector<double> grade;
To insert a grade to the vector you can use grade.push_back(someGrade);

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;
}

Struggling with creating a function that stores user input to any chosen vector (using c++)

This is what I have so far...
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> list1;
vector<int> list2;
void listAdd(int n, vector<int>v) {
while (n != 0) {
v.push_back(n);
cin >> n;
}
}
void printList(vector<int>v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
int main() {
int nInput;
cout << "Please enter numbers for list1... (end with a '0') " << endl;
cin >> nInput;
listAdd(nInput, list1);
printList(list1);
return 0;
}
I basically want all numbers entered by the user (until they enter a 0) to be stored in the vector called list1. Then later i can call the same function to add numbers to another vector...
Help really appreciated :)
you need to pass the vectors by reference
void listAdd(int n, vector<int>& v);
void printList(vector<int>& v);

Sum of elements in a vector?

How would I find the sum of the elements in a vector that was inputted by a user? I tried searching for a method to do so everywhere online but couldn't really find one online that explained it really well, nor was it explained in class too much unfortunately.
So I basically have the vectors inputted by a user here, but I have no idea how to use it to take the sum of it? (printvector is only there because I have to present what the user put in to the user before telling the user the sum)
#include <iostream>
#include <vector>
using namespace std;
void fillVector(vector<int>&);
void printVector(const vector<int>&);
int main()
{
vector<int> VectorQuantities;
fillVector(VectorQuantities);
printVector(VectorQuantities);
return 0;
}
void fillVector(vector<int>& newVectorQuantities)
{
cout << "Type in a list of numbers, and type in -1 as the last number when you are finished: ";
int input;
cin >> input;
while (input != -1) {
newVectorQuantities.push_back(input);
cin >> input;
}
cout << endl;
}
void printVector(const vector<int>& newVectorQuantities) {
cout << "Vector: ";
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
cout << newVectorQuantities[i] << " ";
}
cout << endl;
}
You can use std::accumulate().
#include <algorithm>
std::vector<int> vec = ...;
int vecSum = std::accumulate(std::begin(vec), std::end(vec), 0);
The accumulate() function is really just a left fold, and by default it uses the + function to combine elements.
Try this:
void printSum(const vector<int>& newVectorQuantities) {
cout << "Sum: ";
int sum = 0;
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
sum = sum + newVectorQuantities[i];
}
cout << sum << " ";
}
(Using your style for the function, not modern C++.)