简体   繁体   English

在 C++ 中使用向量在带有循环的动态数组中插入值

[英]insert value in dynamic array with loop using vector in c++

I want to insert value in dynamic array k .我想在动态数组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).正在尝试读入尚不存在的vector位置( k是一个具有零元素的空容器)。

You want to first read in the integer and then add it to the vector like so:您想先读入整数,然后将其添加到vector如下所示:

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);或者,您可以先调整k大小,以便通过执行k.resize(n);在您要访问的所有索引处都有元素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.在读入n (或立即以正确的大小创建它)之后,您现有的代码就可以了。

std::vector::operator[] does not resize the container. std::vector::operator[]调整容器。 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 [] .由于 vector 是动态数组,因此您应该使用push_back而不是 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 .稍后您始终可以使用push_back再次向向量添加新元素。

You will need to use push_back in this case should be something like this:在这种情况下,您需要使用push_back应该是这样的:

#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.这是一个示例代码,但应该可以让您了解如何使用 Vectors 和 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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