-2

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

Rupesh
  • 850
  • 2
  • 13
  • 30
  • 6
    `std::vector k(n);` - this should be covered in your C++ textbook. –  Aug 25 '18 at 18:35
  • You’re not declaring the size of the vector. use std::vector k(n) or see push_back http://www.cplusplus.com/reference/vector/vector/push_back/ – Norhther Aug 25 '18 at 18:36
  • Possible duplicate of [Vector going out of bounds without giving error](https://stackoverflow.com/questions/16620222/vector-going-out-of-bounds-without-giving-error) –  Aug 25 '18 at 18:37
  • 3
    Use [insert](https://en.cppreference.com/w/cpp/container/vector/insert) or `push_back`methods. – Ripi2 Aug 25 '18 at 18:37

4 Answers4

2

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.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
2

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.

eneski
  • 1,575
  • 17
  • 40
0

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

Hasan Patel
  • 412
  • 7
  • 19
-1

you don't need to take another variable just write

vector<int>k

for(int i = 0 ; i< n ; i++) {
     
     k.push_back(i);
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103