I am on Ubuntu 18.04 using the default c++ compiler it comes with. I am trying to get the size of vector required from the keyboard and eventually fill a vector with the increasing value of i in the makeGaps function. I would then like to return a filled vector to my variable x. However, when I run the code below, after it displays the "enter gap size" it does nothing even after I supply an integer. No output, no errors and also in code blocks all the debugger icons go gray. The code also doesn't
terminate and I cannot figure out what is wrong.
#include <iostream>
#include <vector>
using namespace std;
vector<int> makeGaps (int size){
vector<int> vectorOfGaps(size);
for(int i = 0; i <= vectorOfGaps.size();i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
void printV(vector<int> collection){
for (int i = 0; i <= collection.size(); i++){
cout << collection[i]<< '\n';
}
}
int main()
{ //get the number of gaps required
int numberOfGaps;
cout << "Enter gap size";
cin >> numberOfGaps;
vector<int> x = makeGaps(numberOfGaps);
printV(x);
return 0;
}
Also if i run it in the terminal that comes with vs code it crashes my machine.
Vectors in c++ are dynamically sized.
You can create a vector without a size argument in the constructor then push size number of elements like so:
vector<int> makeGaps (int size){
vector<int> vectorOfGaps;
for(int i = 0; i < size;i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
Edit: Also, as someone already pointed out in your comments, it appears you had an off by one error in your for loop. If the for loop runs until x <= size, it will iterate size+1 number of times.
Related
I am writing a code that takes an array of 10 and collects user input. I want to print out the array after the user has finished putting all the values into it. The problem is that when I printout the array it gives me a bunch of garbage values and a weird output. I am not sure why it is doing what it is doing.
This is my code:
#include <iostream>
#include<ctime>
using namespace std;
int main(){
int num;
int arr[10] = {0};
cout<<"Enter 10 numbers: "<< endl;
for(int i = 0; i < 10; i++){
cin>>arr[i];
}
for(int i = 0; i < sizeof(arr); i++){
cout<<arr[i]<< " ";
}
return 0;
}
That is because you are running the loop from 0 till sizeof(arr), here sizeof(arr) means the size of array in bytes. Which happens to be sizeof(int) times the number of elements in the array.
So if we consider sizeof(int) to be 4bytes(i.e. each int takes 4bytes in memory), and number of elements to be 10, then it would be 4*10 = 40. So the for loop would run for 40 times.
Instead do the following:
#include <iostream>
#include<ctime>
using namespace std;
int main(){
int num;
int arr[10];
cout<<"Enter 10 numbers: "<< endl;
for(int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++){
cin>>arr[i];
}
for(int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++){
cout<<arr[i]<< " ";
}
return 0;
}
As pointed out by #user4581301, it's better to make the loop stop taking input at (sizeof(arr)/sizeof(arr[0])), as the size can be changed laterwards.
I have corrected it. It will work now.
Why you are getting garbage values is very well explained in the other answers. You can use std::begin and std::end or range-based for-loop here for iterating through the array. C++ is smart enough to deduce the length of the array for you.
int main(){
int arr[10]{0};
/* Take inputs from the console and fill the array here. */
auto start = std::begin(arr);
auto end = std::end(arr);
for(; start!=end; ++start)
std::cout<<*start<<" ";
// Or using range-based for-loop
for(auto val: arr)
std::cout<<val<<" ";
}
sizeof(arr) is the total size in bytes of the array, not the number of elements. That's probably 40 rather than 10, Because the typical compiler targeting desktop PC hardware uses a 32 bit int at this time.
If your compiler's up to date and supports at least the C++17 Standard revision, use std::size to get the number of elements in the array, but a better option (supported back to C++11) is to use range-based for loops and let the compiler figure out the bounds for you. This makes changes to the count of elements in arr self-managing.
Eg:
for(auto & val:arr){
cin>>val;
}
for(auto & val:arr){
cout<<arr[i]<< " ";
}
If range-based for and std::size are not available, define and use a constant value everywhere you use 10 or sizeof(arr).
Eg:
const int ARR_SIZE = 10;
and then the definition of arr becomes
int arr[ARR_SIZE] = {0};
and the control for both for loops become
for(int i = 0; i < ARR_SIZE; i++)
This allows you to vary the size of arr with only one change required to make the code function correctly. This is also less cumbersome than repeating sizeof(arr)/sizeof(arr[0]) everywhere the number of elements in arr is needed.
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.
I am a beginner to C++ syntax. Now, I need to create an mxn 2D array in C++ to use it in another project. I have looked at other answers which involve using tools like vector, etc. Many tools are not working on my Visual Studio 15 i.e. for vector I can not define with std::vector without a message like vector is not in std. So, I have wrote the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i; int j; int row[5][10] = {};
for (int j = 0; j < 10;)
for (int i = 0; i < 5;)
{
row[i][j] = 500;
int printf(row[i][j]);
i++;
j++;
cout << "Array:" << row[i][j] << endl;
}
return 0;
}
Surely, this is not the correct syntax. So the output is beyond my expectation. I want to create an m*n array with all the elements being the same integer; 500 in this case. That is, if m=3, n=2, I should get
500 500 500
500 500 500
There's a couple things wrong with your current code.
The first for loop is missing curly brackets
You're redefining int i and int j in your for loop. Not a complilation issue but still an issue.
You're using printf incorrectly. printf is used to output strings to the console. The correct line would be printf("%d", row[i][j]);
If you want to use a vector, you have to include it using #include <vector>. You can use a vector very similar to an array, but you don't have to worry about size.
You seem to be learning. So, I did minimal correctios to make it work. I suggest you to make modifications as per your needs.
#include <iostream>
using namespace std;
int main()
{
int row[5][10] = {};
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 5; i++) {
row[i][j] = 500;
cout << row[i][j] << " ";
}
cout << endl;
}
return 0;
}
Care and feeding of std::vector using OP's program as an example.
#include <iostream>
#include <vector> // needed to get the code that makes the vector work
int main()
{
int m, n; // declare m and n to hold the dimensions of the vector
if (std::cin >> m >> n) // get m and n from user
{ // m and n are good we can continue. Well sort of good. The user could
// type insane numbers that will explode the vector, but at least they
// are numbers.
// Always test ALL user input before you use it. Users are malicious
// and incompetent <expletive delteted>s, so never trust them.
// That said, input validation is a long topic and out of scope for this
// answer, so I'm going to let trapping bad numbers pass in the interests
// of keeping it simple
// declare row as a vector of vectors
std::vector<std::vector<int>> row(m, std::vector<int> (n, 500));
// breaking this down:
// std::vector<std::vector<int>> row
// row is a vector of vectors of ints
// row(m, std::vector<int> (n, 500));
// row's outer vector is m std::vector<int>s constructed with
// n ints all set to 500
for (int j = 0; j < n; j++) // note: j++ has been moved here. This is
// exactly what the third part of a for
// statement is for. Less surprises for
// everyone this way
// note to purists. I'm ignoring the possible advantages of ++j because
// explaining them would muddy the answer.
// Another note: This will output the transverse of row because of the
// ordering of i and j;
{
for (int i = 0; i < m; i++) // ditto I++ here
{
// there is no need to assign anything here. The vector did
// it for us
std::cout << " " << row[i][j]; // moved the line ending so that
// the line isn't ended with
// every column
}
std::cout << '\n'; // end the line on the end of a row
// Note: I also changed the type of line ending. endl ends the line
// AND writes the contents of the output stream to whatever media
// the stream represents (in this case the console) rather than
// buffering the stream and writing at a more opportune time. Too
// much endl can be a performance killer, so use it sparingly and
// almost certainly not in a loop
}
std::cout << std::endl; // ending the line again to demonstrate a better
// placement of endl. The stream is only forced
// to flush once, right at the end of the
// program
// even this may be redundant as the stream will
// flush when the program exits, assuming the
// program does not crash on exit.
}
else
{ // let the use know the input was not accepted. Prompt feedback is good
// otherwise the user may assume everything worked, or in the case of a
// long program, assume that it crashed or is misbehaving and terminate
// the program.
std::cout << "Bad input. Program exiting" << std::endl;
}
return 0;
}
One performance note a vector of vectors does not provide one long block of memory. It provides M+1 blocks of memory that may be anywhere in storage. Normally when a modern CPU reads a value from memory, it also reads values around it off the assumption that if you want the item at location X, you'll probably want the value at location X+1 shortly after. This allows the CPU to load up, "cache", many values at once. This doesn't work if you have to jump around through memory. This means the CPU may find itself spending more time retrieving parts of a vector of vectors than it does processing a vector of vectors. The typical solution is to fake a 2D data structure with a 1D structure and perform the 2D to 1D mapping yourself.
So:
std::vector<int> row(m*n, 500);
Much nicer looking, yes? Access looks a bit uglier, though
std::cout << " " << row[i * n + j];
Fun thing is, the work done behind the scenes converting row[j][i] to a memory address is almost identical to row[j*n+i] so even though you show more work, it doesn't take any longer. Add to this the benefits you get from the CPU successfully predicting and reading ahead and your program is often vastly faster.
I'm working on a program in C++ that is supposed to read in a file, store the content of the file into a 2D array, assign characters to each of the numbers in the array and store in a char array, and print both of these arrays. It's then supposed to go through the initial array and make sure that each number doesn't differ in value from it's neighboring numbers by more than 1, correct these errors by replacing these numbers with the value of the average of their neighbors, assign characters to this corrected array as it did before, and print both arrays.
The character assignments go as follows:
0=blank
1=.
2=,
3=_
4=!
5=+
6=*
7=#
8=$
9=&
I have the code written that opens the file and loads the array, but I have no idea where to go from there. To me the obvious, although probably not best, way to do the assignments is to go through the array with a for loop and use a series of if statements to check for the value of the number at each index and assign the appropriate symbol. I'm sure there's a better way to accomplish this.
Here is the code I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream prog;
prog.open("../prog1.dat");
//If file can't be opened, exit
if (!prog) {
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
else {
while (!prog.eof()) {
int size = 100, i, j;
prog >> size;
int **numArray = new int* [size];
for(i = 0; i < size; i++) {
numArray[i] = new int[size];
for(j = 0; j < size; j++) {
prog >> numArray[i][j];
}
cout << endl;
}
for(i = 0; i < size; i++) {
for(j = 0; j < size; j++) {
cout <<numArray[i][j] << " ";
}
cout << endl;
}
prog.close();
return 0;
}
}
}
I'm extremely new to this programming language, this is actually my first program I've done in C++ and I'm literally learning as I go. Any suggestions would be greatly appreciated.
In this code You have not put a check on the difference with neighbour.
Moreover their is no need for 2 nested for loops that is a very big overhead. You could have printed the numArray in the first nested for loop.
According to you it is your first programming assignment and you are already using double pointers and nested loops and also the way you checked the file is opened or not. Are you sure it's your first assignment
Please i am stuck at this question for half an hour and can't find why the error comes?
Problem code : test
Life, Universe and Everything
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0];
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
Your code tries to access non-existing array elements, which causes segfault. You should stop your loop before the array index gets larger than the length of the array minus 1:
int a[20];
for (i = 1; i < 20 && a[i - 1] != 42; i++)
{
// ...
}
Apart from limit problem, your printing elements without initializing them
//for i = 1, a[i] is uninitialized
cout<<a[i]<<"\n";
On accessing a local variable (like this), you're likely to get garbage value.
This might be better substitute for what you are trying to do:
int a[20],i;
for(i=0;i < 20;i++)
{
cin>>a[i];
if (a[i] == 42)
break;
cout<<a[i]<<"\n";
}
You are trying to print the uninitialized data...
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0]; // a[0] uninitialized
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
In the for loop get the data first and then print it.Your array size is 20 but you are trying to write upto 42.
You use array values before initializing them. C++ doesn't initialize non-static arrays for you unless you tell it to, so $DEITY knows what's in there. And technically, whatever's in there could cause an exception...or any number of other things. (For ints, on an x86 machine, that's actually highly unlikely. But elsewhere, it's possible.)
The user can enter more than 20 numbers. That's really just a special case of the more general problem, though: You allow unknown number of entries, but aren't able to accept them all without crashing.
If you don't know beforehand how many objects there will be, use a vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> a;
int entry;
cin>>entry;
// Oh, yeah. This. You really, *really* want to check `cin`.
// Otherwise, if the user decided to type "i like cheese", you'd loop
// forever getting zeros while cin tried to parse a number.
// With the array, that'd typically cause a segfault near instantly.
// With a vector, it'll just eat up all your CPU and memory. :P
while (cin && entry != 42) {
a.push_back(entry);
cout << entry << "\n";
cin >> entry;
}
return 0;
}