简体   繁体   中英

insert value in dynamic array with loop using vector in 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

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.

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 .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM