C++ Substracting adjacent elements in a vector [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a code to subtract the adjacent elements of a vector and enter the answer into a new vector. However, my code isn't working. What exactly is wrong with it?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length;
vector<int>values;
vector<int>values2;
cout << "Enter the length of the vector";
cin >> length;
values[0]=1; values[1]=2; values[2]=3; values[3]=4; values[4]=5;
for(int i=0; i<length; i++)
{
cout<<"Enter the " << i <<"th element of the vector";
cin >> values[i];
}
for (int i=0; i<length-1; i++)
{
values2[i]=values[i+1]-values[0];
}
return 0;
}

You need to size the vectors accordingly before accessing elements. You can do that on construction, or using resize.
vector<int>values(5/*pre-size for 5 elements*/); and similar for values2 would fix your problem.
Currently your program behaviour is undefined.
If you want to subtract adjacent elements, then shouldn't you have values2[i]=values[i+1]-values[i];?

The line of code:
values2[i]=values[i+1]-values[0];
will take the looked-at element away from the first element each time.
Did you mean:
values2[i]=values[i+1]-values[i];
?

Related

Can't erase digits from c++ string by using the 'erase' function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using c++ 14.
I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.
The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.
Example:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.
code:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
In the first sentence you were writing that you are using C++14.
In "more modern" C++ the usage of algorithm is recommended. So normally you would not use C-Style For loops.
The standard approach that you can find everywhere, is a combination of erase with std::remove_it. You will find this construct in many many examples.
Please consider to use such a solution instead of a for loop.
You can even include the output in an algorithm using std::copy_if.
Please see:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "\n\n";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
If there's two digits next to each other, it skips the second digit. This happens because the index, i, keeps going up, even though everything got shifted over:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
To fix this, we just have to decriment i after erasing a digit:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}

Segmentation Error in For loops while submission [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
This Code passed the Compile and run Test, but when I try to submit It in HackerRank, Its saying that it's a segmentation error.
// Sample code to perform I/O:
#include <iostream>
using namespace std;
int main() {
int n;
int i;
int a[i];
cin >> n;
for(i=0;i<n;i++)
{
cin >> a[i]; //Reading Input to STDIN
}
for(i=n-1;i>=0;i--)
{
cout << a[i] << endl; // Writing output to STDOUT
}
return 0;
}
RESULT: Runtime Error - SIGSEGV
i is not initialized so you have undefined behavior. Never use a variable before initializing it.
Use vector instead of the array:
#include <vector>
int main() {
int n;
//int i; you don't need i anymore
vector<int> a;
cin >> n;
a.reserve(n);
for(int i=0;i<n;i++)
{
cin >> a[i]; //Reading Input to STDIN
}
by using int a[i]; you have two problems:
i must be known in compile time(you cannot make it dynamic then)
you store the array in stack memory, meaning the size will be very
limited
vector is a container which allows you to resize the array anytime. It
uses heap memory for storing data.

Nested loops and modulus c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learning C++ and I have a problem with my program. It should print out following if n=11:
*---------*
-*-------*-
--*-----*--
---*---*---
----*-*----
-----*-----
----*-*----
---*---*---
--*-----*--
-*-------*-
*---------*
This is my code, which works correctly with n=5, but not with greater numbers:
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter size (n x n): " << endl;
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i%n==j%n) cout << '*';
else if (i%(n-i)==j%(n-j)) cout << '*';
else cout << '-';
}
cout << endl;
}
return 0;
}
This is being printed out if n=11:
*---------*
-*----*--*-
--*-----*--
---*---*---
----*------
-----*-----
-*----*--*-
---*---*---
--*-----*--
-*----*--*-
*---------*
I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.
Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?
This problem is really simple to debug.
Take a look at the first erroneous *. It appears at the position with i=1, j=6. With n=11, your condition i%(n-i)==j%(n-j) becomes 1%(11-1) == 6%(11-6) which is effectively true because the expression evaluates to 1 on both sides.
What is behind this expression? Why do you use this kind of if to determine whether the cell belongs to the second diagonal? Try to write down each pair i, j which should be printed on the second diagonal, and you should notice a more simple pattern.
P.S. In the expression if (i%n==j%n) you don't have to take operands modulo n, because both of them are less than n, so it is redundant and may be rewritten simply as if (i == j).

an error i can't seem to find [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a beginner and still learning C++ I was playing with vectors to see what will happen.whenever I start it gives me a debug error.
here is the code
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
}
Problem lies in the order of operations inside while() loop:
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
i starts from 0. In each iteration, you push_back an element and then print it using counter i - after its incrementation. So, num[i] refers to a non-yet-existing element.
Change your code to:
while (i < 1000)
{
num.push_back(i + 1);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
The index of a vector starts from zero. In your code you were always accessing 1 index ahead of what you were updating(or pushing).
When I incremented i after the two statements it worked fine.
I dont know how but it worked fine.
Thanks everyone.
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
}
Make sure that you are using
#include<vector>
#include<iostream>
using namespace std;

My C++ program not working properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to make a program in C++ that will read numbers and then arrange them in ascending order. The numbers can be infinite, so the program should read numbers until any particular value is entered to terminate the reading process. I have written below code but is not working and showing undesired output. I will be so thankful if someone will help me.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p,*q,i=1,j,k,temp;
p=(int*)malloc(sizeof(int));
cin>>*p;
while((*p)!=-1) //read until -1 is entered
{
i++;
p=(int*)realloc(p,sizeof(int)*i);
q=p;
p=p+(i-1); //going to next address to read
cin>>*p;
}
p=q;
for(j=1;j<i;++j)
{
for(k=0;k<i-j-1;++k)
{
if((*(p+k))>(*(p+k+1)))
{
temp=*(p+k);
*(p+k)=*(p+k+1);
*(p+k+1)=temp;
}
}
}
cout<<"\n";
for(j=0;j<i-1;++j)
{
cout<<*(p+j)<<" ";
}
}
Expanding on my comment, here is what an actual C++ solution might look like:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers;
int number = -1;
std::cin >> number;
while (number != -1)
{
numbers.push_back(number);
number = -1;
std::cin >> number;
}
std::sort(numbers.begin(), numbers.end());
for (int x : numbers)
{
std::cout << x << ' ';
}
std::cout << '\n';
}
After
p=p+(i-1);
p is no longer a pointer that is valid to realloc.
Replace
p=p+(i-1);
cin>>*p;
with
cin >> p[i-1];
and get rid of q.
(You can use cin >> *(p + i - 1); if you insist on obfuscation.)
Your sorting routine also becomes much more readable if you replace the pointer arithmetic with indexing.