根据索引删除向量元素 [英] Remove vector elements based on the index

查看:152
本文介绍了根据索引删除向量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据索引删除向量的元素,例如所有偶数索引元素。
我已经阅读关于擦除删除idiom,但不能看到如何应用它。
这是我试过的:

I wanted to remove the elements of the vector based on the index, say all the even indexed elements. I have read about the erase remove idiom but can't see how to apply it. This is what I tried:

    vector<int> line;
    line.reserve(10);
    for(int i=0;i<10;++i)
    {
      line.push_back(i+1);
    }
    for(unsigned int i=0;i<line.size();++i)
    {
      //remove the even indexed elements
      if(i%2 == 0)
      {
        remove(line.begin(),line.end(),line[i]);
      }
    }
line.erase( line.begin(),line.end() );

这将擦除整个向量。我希望只能删除已被删除算法标记的元素。

This erases the entire vector. I was hoping to only remove the elements that had been marked by the remove algorithm.

然后我尝试了

for(unsigned int i=0;i<line.size();++i)
    {
      //remove the even indexed elements
      if(i%2 == 0)
      {
        line.erase( remove(line.begin(),line.end(),line[i]),line.end() );
      }
    }

同时删除,索引似乎移动,而迭代的向量。

This again doesn't work as there is a problem while removing, the indices seem to shift whilst iterating over the vector. What should be the correct approach to accomplish this.

推荐答案

在线演示

Online Demo:

#include <vector> 
#include <algorithm>
#include <iostream>

/*Check if Index is Even or Odd*/ 
bool is_IndexEven(int i) 
{
   static int k = 1;

   /*Handle Index 0 as special case as per choice*/
   if(k == 1)
   {
       k++;
       return false;
   } 

   if(k++ % 2)
       return true;
   else 
       return false; 
 }

int main() 
{
    using namespace std;
    int elements[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // create a vector that holds the numbers from 0-9.
    vector<int> v(elements, elements + 10); 

    /*Display elements before removal*/    
    vector<int>::const_iterator iter = v.begin();
    cout<<"Before\n";

    for(iter;iter!= v.end();++iter)
    {
        cout<<*iter;
    }

    /*Remove_if + Erase Algorithm for one step removal*/
    v.erase( remove_if(v.begin(), v.end(), is_IndexEven), v.end() ); 

    /*Display result after elements removed*/
    cout<<"\nAfter\n";
    iter = v.begin();
    for(iter;iter!= v.end();++iter)
    {
       cout<<*iter;
    }

    return 0;
}

这篇关于根据索引删除向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆