How to input to vector correctly in C++ - c++

When I try to input to vector by following code, I get a segmentation fault as shown below.
I defined the vector and set N, and tried to input a vector with N elements.
What is the root cause of this?
#include <iostream>
#include <vector>
using namespace std;
int N;
vector<int> A(N);
int main(){
cin>>N;
for(int i=0;i<N;i++) cin>>A[i];
}
[ec2-user#ip-10-0-1-187 ]$ ./vector_input
1
1
Segmentation fault

That's because constructor of A is called with N=0. When you input N, it doesn't affect the vector at all. If you really want to keep using globals, then use std::vector::resize but the recommended way would be:
int main(){
std::size_t n;
std::cin >> n;
std::vector<int> A(n);
for(auto & x : A) std::cin >> x;
}

This happened because N was never initialized and it was used for initiating vector. So, your code produces undefined behavior.
You need to take input first, and then initialize the vector.
Also, avoid using using namespace std;. And there's no real need to initialize A and N in a global scope.
NOTE: To avoid undefined behavior further you enable this flag while compiling C++ programs.
-fsanitize=undefined,address
Code:
#include <vector>
#include <iostream>
int main(void)
{
int N;
std::cin >> N;
std::vector<int> A(N);
for(auto &i : A)
std::cin >> i;
return 0;
}

The variable N used for initialization is not initialized
int main(){
int n,a;
vector<int> vec;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a;
vec.push_back(a);
}
}

Related

How to get multiple input from user in one line c++

5
1 2 3 4 5
the first line is how many input will user give.
and the second line is the input from the user. basically it's "c >> a >> b >> c;" but it's up to the user how many input they want.
The answer is quite simple. Read an int n indicating the number of items, then declare a std::vector<int> and read in n elements in a loop, pushing each onto the vector. This can be done either with an explicit for loop, or using STL functions.
It's simple to read input and store in std::vector. You can resize the vector to hold n elements by passing n to its constructor. Then you can read into the std::vector like you do for a normal array.
#include <vector>
#include <iostream>
int main()
{
int n;
std::cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; i++)
std::cin >> v[i];
for (int i = 0; i < n; i++)
std::cout << v[i] << std::endl;
}
I would be inclined to use a std::vector over any other data type.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector <int> xs;
int n;
std::cin >> n;
// method 1
std::copy_n( std::istream_iterator <int> ( std::cin ), n, std::back_inserter( xs ) );
// method 2
int x; while (n--) { std::cin >> x; xs.push_back( x ); }
In general, your goal should not be to do things “in one line”, but to do things correctly and succinctly, favoring correctness over terseness.

timeout: the monitored command dumped core

i am running this code in online compiler showing dumped core error this program finding highest product of two pair.
#include <bits/stdc++.h>
using namespace std;
void maximumproductpair(int arr[],int n){
sort(arr,arr+n);
reverse(arr,arr+n);
int prod;
for(int i=0; i<n; i++){
cout<<arr[i];
}
prod=prod*arr[0];
prod=*arr[1];
cout<<prod;
}
int main()
{
int t,n;
int arr[n];
cin>>t;
cout<<"\n";
cin>>n;
cout<<"\n";
while(t--){
for(int i=0; i<n;i++){
cin>>arr[i];
}
}
maximumproductpair(arr,n);
return 0;
}
in code everything fine then why this error?
Mistake 1
The problem is that your t and n variables are uninitialized. This means both t and n have garbage value. And when you wrote:
int t,n;
int arr[n];//UNDEFINED BEHAVIOR because n has garbage value
You have undefined behavior because n has garbage value.
This is why it is advised that
always initialize built in types in local/block scope.
Mistake 2
Second, note that in C++ the size of an array must be a compile-time constant. So take for example the following code snippets:
int n = 10;
int array[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int array[n]; //CORRECT
Similarly,
int n;
cin >> n;
int array[n]; //INCORRECT becasue n is not a constant expression
Also note that some compilers provide compiler extension that lets you have variable length array. You can read more about it at Why aren't variable-length arrays part of the C++ standard?.
If you want to take the size of the array as input from the user then you should use dynamic sized containers like std::vector :
int n;
cin >>n;
std::vector<int> array(n);// CORRECT, this creates a vector of size n of elements of type int
Also see Why should I not #include <bits/stdc++.h>?.

Input different values into set without using extra variable (C++)

I want to store values into set without using extra variable.
int n,x;
set<int> s;
cin>>n;
for(int i=0;i<n;i++)
{
cin >> x;
s.insert(x);
}
This is what i have been doing till now, was wondering if i could remove x, as this variable is useless.
I am new to C++. Forgive me if my doubt is very naive.
was wondering if i could remove x
Sure.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
int main() {
std::set<int> s;
int n;
std::cin >> n;
std::copy_n(std::istream_iterator<int>{std::cin}, n,
std::inserter(s, s.begin()));
}

How can I label and store (n) number of (a) inputs like a1, a2

#include <iostream>
using namespace std;
int n, a, k;
main(){
cin>>n;
for(k=1; k<=n; k++){
cin>>a;}}
how can I store inputs to use them in future operations, I'm beginner programmer, I'm looking for easiest way for that.
If you want to read n integers you can use a vector:
#include <iostream>
#include <vector>
int main()
{
int n;
std::vector<int> vec; //Better try to use namespaces
//Some spaces add clarity
std::cin >> n;
vec.resize(n);
for(int k=0; k<n; k++) //Define local varibales relative to loop for iterator
{
std::cin >> vec[k];
}
return 0; //Always return a code at the finish of the program
}

I can not enter the data for arrays

I want to enter n times values for c and e arrays. The following program doesn't allow me to even enter the value of 'n'. Could you tell me where is the mistake?
#include <iostream>
using namespace std;
int main()
{
int n,c[n],e[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
"n" should be defined before using it to fix array size. Also, const int or constant should be used to declare array size not plain int.
In order to use plain datatype, you can initialize array dynamically like
vector<int> a(n); or
int a = new int[n]
int n,c[n],e[n];
This declaration creates arrays c and e on stack with random size, because n as an automatic variable is initialized with random value. Instead you need to dynamically create arrays on heap or use std::vector.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
int n;
vector<int> v;
std::cin >> n;
v.resize( n);
for( int i = 0; i < n; ++i) {
cin >> v[i];
}
for( int i = 0; i < n; ++i) {
cout << v[i];
}
return 0;
}
http://ideone.com/QhgfNv
In the line of
int n,c[n],e[n];
Computer don't know the exact value of 'n', so it can't alloc memory of array.
The simplest solution is create array with fixed number, and check n after you know the value of n as follows:
int n, c[1024], e[1024];
cin >> n;
if (n > 1024) { /* error */ }
The other way is malloc memory after u know the value of n:
int n;
cin >> n;
int *c = new int[n];
int *e = new int[n];
xxxx
delete [] c;
delete [] e;
You can try something like this:
#include <iostream>
using namespace std;
int main()
{
int temp = 100; /*Random value*/
int c[temp];
int e[temp];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
Now, I chose temp as 100, but you can do big as your int can store. Now, if n is lower than temp, your for cycle will let you save your values without troubles.