insert value in dynamic array with loop using vector in c++ - c++

I want to insert value in dynamic array k. this is my code.
cin >> n;
std::vector<int> k;
for(int i = 0 ; i< n ; i++) {
cin >> k[i];
}
But it is not storing any value. I don't know why, please help me

Because vector is dynamic array, you should specify that you want to add a new element by using push_back instead of operator [].
Following piece of code would work:
for(int i = 0 ; i< n ; i++) {
int element;
cin >> element;
k.push_back(element);
}
Or even better you can initialise your vector object by calling the constructor which takes initial container size as an parameter. Later you always can add new elements to the vector again by using push_back.

cin >> k[i]; is trying to read into a location of the vector that does not exist yet (k is an empty container with zero elements).
You want to first read in the integer and then add it to the vector like so:
int num;
cin >> num;
k.push_back(num);
Alternatively you could resize k first, so it has elements at all indices you are going to access, by doing k.resize(n); after reading in n (or just create it with the right size right away) and then your existing code will be fine.
std::vector::operator[] does not resize the container. It only accesses pre-existing elements and if the accessed element is not within bounds of the container the behaviour is undefined.

You will need to use push_back in this case should be something like this:
#include <vector>
int main ()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some Numbers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
This is a sample code but should give you the idea on how to get around with Vectors and push_back.
cheers

you don't need to take another variable just write
vector<int>k
for(int i = 0 ; i< n ; i++) {
k.push_back(i);
}

Related

C++ filling in array with input from another

I'm just taking input for two arrays and manipulating the information. When I take input for both arrays it puts the information from the second into both arrays. In the code below I haven even commented out the input for the second array to see what happens and it still puts the input for M into both arrays. Can anyone see the cause?
int M[0], N[0];
std::cin >> m >> n;
for (int i = 0; i < m; ++i)
{
std::cin >> M[i];
}
for(int i=0; i<m; i++)
{
std::cout << M[i];
}
std::cout << "\n";
for(int i=0; i<n; i++)
{
std::cout << N[i];
}
For starters these declarations
int M[0], N[0];
are invalid, You may not declare an array with zero elements.
Thus the code has undefined behavior.
Secondly variable length arrays are not a standard C++ feature. Either declare the arrays with the potentially maximum number of elements or use the standard container std::vector.
the code that you just showed has a problem.
You print only M because you didn't do the input for-loop for the N array. So the array N has nothing inside.
So to fix this do another for and ask for input in the array N.
for (int i = 0; i < m; ++i)
{
std::cin >> N[i];
}
Hope this helps.

What's the difference between vector<vector<int>> vec and vector<vector<int>> vec(n)? [duplicate]

This question already has answers here:
Why does my vector print out all zeroes?
(4 answers)
Closed 1 year ago.
I was trying to access vector elements today, so when I used vector<vector<int>> vec and then added elements to it. I was able to access those elements like vec[1][2].
But when I use vector<vector<int>> vec(n) and then added elements, I was not able to access the elements using vec[1][2]. I keep getting a segmentation error. Does anyone know what am I missing here?
I am adding the elements to the vector through with the help of the below code snippet.
int n;
cin >> n;
vector<vector<int>> vh;
int size, input;
for (int i = 0; i < n; i++)
{
vector<int> temp;
cin >> size;
for (int j = 0; j < size; j++)
{
cin >> input;
temp.push_back(input);
}
vh.push_back(temp);
}
I think I can guess what the problems is...
When you use the constructor with an argument:
vector<vector<int>> vh(n);
you create a vector with the size n, it means it will already have n elements, where each element will be a default-constructed vector<int>. Which means that each vector will be empty.
Then you push back a new vector:
vh.push_back(temp);
This will increase the size of the vector. After one such push_back call the size of vh will be n + 1. The new vector you add will be at index n, i.e. vh[n] is the new vector.
If you set the size when you define the vector, then you need to use indexing and assignment to set the sub-vectors:
vh[i] = temp;
To summarize:
Either you create an empty vector and push back new elements:
vector<vector<int>> vh;
and
vh.push_back(temp);
Or you create a vector with a size, and use indexing and assignment:
vector<vector<int>> vh(n);
and
v[i] = temp;
Don't mix these ways.
Now when you got your current code working (hopefully) and understand how these things work a little better, it's time to show a way how to do your code in a more "C++-ish" way... :)
// The first part is much like your current code
size_t n;
std::cin >> n;
std::vector<std::vector<int>> vh(n);
// Now iterate over all the elements in the vector
for (auto& v : vh)
{
// Get the size of the current sub-vector
size_t size;
std::cin >> size;
// Create the vector with size elements
v = std::vector<int>(size);
// Read size integers into the vector
std::copy_n(std::istream_iterator<int>(std::cin), size, begin(v));
}

How do you build an array with certain elements from another array in C++?

Given a one-dimensional array with n integers and a whole number A,
list how many elements are larger than A
and build an array with these elements.
I'm having problems with the last part.
The answer is almost already in the question
(giving it here, assuming that the question is really as simple as it confusingly seems to me):
count the relevant elements, print/"list" that number
create a new std::array of that size
(consider asking whether using a std::vector is an option, it would allow doing this in a single pass)
(explicitly do NOT attempt to use the non-C++ construct of C-style VLA, variable length arrays, like std::cin>>n; int NewArray[n];)
go through the input array again and copy the relevant elements to the new array
count indexes in both arrays separatly, because the index in the first array will soon be larger than the index into the new array
Note:
I intentionally do NOT provide code, because I feel that the compromise described here should be applied: How do I ask and answer homework questions?
First you have to create two arrays (if you can use std::vectors, i think they will work nicely in this scenario) - first one as a base, and the second one for storing values larger than A.
Get input of A and n.
Use a for loop to put n values into the base array.
Use a for loop to check if baseArray[i] is bigger than A, if true - put baseArray[i] into the second array (if youre using std::vectors do it by push_back()).
Display the number of values higher than A by secondArray.size().
Without using the std::vector:
#include <iostream>
using namespace std;
int main()
{
int n;
int A;
int howManyBiggerThanA = 0;
cin >> n;
cin >> A; //you haven't specified how the n and A are supposed to be implemented so ill assume its going to happen this way
int *array = new int[n]; //creating an array with n integers
array[0] = A; //assigning A to the array as specified in the question - "and a whole number A"
for (int i = 1; i < n; i++)
{
array[i] = i; //filling the array with n integers of value 1 to n-1 (u havent specified what values are supposed to be inside this array)
}
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
howManyBiggerThanA++; //determining how many values are bigger than A
}
}
int *arrayForBiggerThanA = new int[howManyBiggerThanA]; //creating an array for values that are bigger than A
int assistant = 0;
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
arrayForBiggerThanA[assistant] = array[i]; //filling the second array with elements that are bigger than A
assistant++;
}
}
cout << "How many elements bigger than A: " << howManyBiggerThanA << endl;
cout << "Values bigger than A: ";
for (int i = 0; i < howManyBiggerThanA; i++)
cout << arrayForBiggerThanA[i] << ", ";
delete[] array;
delete[] arrayForBiggerThanA;
return 0;
}

Why I can't input into my std::vector in C++

I'm a newbie in C++. I've just learnt about vector in STL.
However, when I tried to input an integer into my vector:
vector<int> v;
cin>>v[i]
The program returned segmentation fault. Please help me out.
Your vector doesn't have any elements in it, so the internal array is null. When you try to read something into it, you're trying to deference a null pointer (resulting in the segfault). Add elements to the vector first:
vector<int> v(100); //Create vector with 100 elements
for(int i = 0; i < 100; i++) {
cin >> v[i];
}
Alternatively, you could read elements into a local variable, then add them into the vector:
vector<int> v;
for(int i = 0; i < 100; i++) {
int new_val;
cin >> new_val;
v.push_back(new_val);
}

Program declaring variables by itself

I am still a ... novice, in c++.
I don't know the name of what I am looking for but
I 've been searching a lot but can't seem to find the answer to following question:
I want to write a program that would declare demanded number of variables.
Example:
int a;
cin>>a;
Now if "a" is 5 (or any other number), I want program to declare 5 more variables,
Names do not matter but let's say...n1,n2,n3,n4,n5.
I've tried array and for loop but can't get it to work.
I got answer on Croatian forum (forum.hr) but the forum is currently offline, so I had no
time to try it out...
It was about using heap instead of stack
Thx in advance
C++ has container classes for this purpose. In particular, you want a vector:
std::vector<int> a(size);
for (int i = 0; i < a.size(); ++i)
std::cin >> a[i];
Declares a vector a of integers of some size and reads its elements, one by one.
If this is C++, the best you can do is using std::vector as it will manage the memory for you.
you can store them in an array:
int a;
cin >> a;
int *number = new int[a]; // allocate an array of size a
for (int i = 0; i < a; i++) {
number[i] = 5 + i; // set your numbers to anything here
}
delete[] number; // otherwise you have memory leak
or better use a vector:
vector<int> number(a);
// iterate with a normal for loop
for (int i = 0; i < number.size(); i++) {
number[i] = 5 + i;
}
..
// or use iterators
for (vector<int>::iterator it = number.begin(); it != number.end(); ++it) {
cout << *it << endl;
}
so you don't have to manage memory.