简体   繁体   English

vector.insert不调整向量大小吗?

[英]vector.insert doesn't resize vector?

i'm trying to create a function that takes in a vector by reference and if it sees a vector entry 2, it would take delete the entry and replace it with 4 copies of 5. 我正在尝试创建一个通过引用接收向量的函数,如果它看到一个向量条目2,它将删除该条目并将其替换为5的4个副本。

so if the vector is 222 (then it is size n = 3), i want 555555555555 as the new vector 所以如果向量是222(那么它的大小n = 3),我想555555555555作为新向量

however, it only works properly for the first few, when the index is < n. 但是,当索引<n时,它仅适用于前几个。

so right now, it would change vector a to be 555522 any ideas how to make the vector resize? 因此,现在,将向量a更改为555522的任何想法如何调整向量的大小?

void replace2 (vector <int>* a, int n){

  for (int i = 0; i < n; ++i){
    if ((*a)[i] == 2){
      (*a).erase((*a).begin() + i);
      for(int j = 0; j < 4; ++j){
      (*a).insert((*a).begin() + i, 5);
            }
        }
      }

}

The problem with using 使用的问题

for ( int i = 0; i < n; ++i ) { ... }

has already been pointed out in one of the comments: 评论之一已指出:

After the first iteration of the loop, (*a)[i] no longer equals 2. Remaining iterations do nothing. 在循环的第一次迭代之后, (*a)[i]不再等于2。其余的迭代则无济于事。

Your function will be simplified if you iterate from the end of the vector and go back. 如果从向量的末尾进行迭代并返回,则会简化您的函数。

Also, pass a reference to the vector instead of a pointer. 另外,将引用传递给向量,而不是指针。

Here's a complete program: 这是一个完整的程序:

#include <vector>
#include <iostream>

void replace2(std::vector <int>& a, int n){
   for (int i = n-1; i >= 0; --i){
      if (a[i] == 2){
         a.erase(a.begin() + i);
         for(int j = 0; j < 4; ++j){
            a.insert(a.begin() + i, 5);
         }
      }
   }
}

int main()
{
   std::vector<int> a{2, 2, 2};
   replace2(a, 3);

   for(auto item : a )
   {
      std::cout << item;
   }

   std::cout << std::endl;
}

See it working at https://ideone.com/0Lip5j . https://ideone.com/0Lip5j上查看它的工作原理

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

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