如何在遍历list,vector,map时删除符合条件的元素

简介: class Pred{public:    bool operator()(int a){        if(a>=6&&a=8&&*it=3&&*it
class  Pred{
public :
    
bool   operator ()( int  a){
        
if (a >= 6 && a <= 7 )
            
return   true ;
        
return   false ;
    }
};
void  f(pair < int , int >  p)
{
    cout
<< p.first << "   " ;
}
int  main(){
    
int  a[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
    list
< int >  b = list < int > ();
    b.assign(a,a
+ 10 );
    vector
< int >  d;
    d.assign(a,a
+ 10 );
    map
< int , int >  c = map < int , int > ();
    
for (list < int > ::iterator it = b.begin();it != b.end();it ++ ){
        c[
* it] =* it;
    }
    
// 删除8,9
     for (list < int > ::iterator it = b.begin();it != b.end();){
        
if ( * it >= 8 &&* it < 10 ){
            it
= b.erase(it);
        }
else {
            it
++ ;
        }
    }
    
// 删除5,6,注意这种写法只适应于list,不适应于vector,因为vector没有remove_if方法
    b.erase(remove_if(b.begin(),b.end(),Pred()),b.end());
    
// 删除3,4
     for (vector < int > ::iterator it = d.begin();it != d.end();){
        
if ( * it >= 3 &&* it <= 4 ){
            it
= d.erase(it);
        }
else {
            it
++ ;
        }
    }

    ostream_iterator < int >  os(cout, "   " );
    copy(b.begin(),b.end(),os);
    cout
<< endl;
    copy(d.begin(),d.end(),os);
    cout
<< endl;
    
// 删除5,6
     for (map < int , int > ::iterator it = c.begin();it != c.end();){
        
if (( * it).first >= 5 && ( * it).first <= 6 ){
            c.erase(it
++ );
        }
        
else {
            it
++ ;
        }
    }
    for_each(c.begin(),c.end(),f);
}
相关文章
|
28天前
|
安全 Java 数据库连接
让我们讲解一下 Map 集合遍历的方式
我是小假 期待与你的下一次相遇 ~
80 43
|
6天前
|
JavaScript 前端开发
如何在Map中获取元素的数量?
如何在Map中获取元素的数量?
25 1
|
2月前
|
存储 安全 Go
Map的遍历与判断键是否存在-《Go语言实战指南》
本文介绍了 Go 语言中对 `map` 的常见操作,包括遍历所有项和判断键是否存在。通过 `for range` 可以遍历 `map` 的键值对、仅键或仅值(需忽略键)。注意,`map` 遍历顺序是随机的。判断键是否存在时,使用双赋值语法 `value, ok := map[key]`,其中 `ok` 表示键是否存在。直接访问不存在的键会返回类型的零值,可能导致逻辑错误。掌握这些机制可更安全高效地处理键值对数据。
|
1月前
|
存储 JavaScript 前端开发
for...of循环在遍历Set和Map时的注意事项有哪些?
for...of循环在遍历Set和Map时的注意事项有哪些?
57 0
使用 entrySet 遍历 Map 类集合 KV
使用 entrySet 遍历 Map 类集合 KV
|
5月前
|
Java 程序员 开发者
悲催,放到 Map 中的元素取不出来了
本文通过一个程序员小明遇到的实际问题,深入探讨了在使用 HashMap 时由于键对象的可变性导致的数据访问异常。
|
5月前
|
DataWorks 关系型数据库 Java
悲催,放到 Map 中的元素取不出来了
悲催,放到 Map 中的元素取不出来了
|
7月前
|
算法
你对Collection中Set、List、Map理解?
你对Collection中Set、List、Map理解?
138 18
你对Collection中Set、List、Map理解?
|
7月前
|
存储 缓存 安全
只会“有序无序”?面试官嫌弃的List、Set、Map回答!
小米,一位热衷于技术分享的程序员,通过与朋友小林的对话,详细解析了Java面试中常见的List、Set、Map三者之间的区别,不仅涵盖了它们的基本特性,还深入探讨了各自的实现原理及应用场景,帮助面试者更好地准备相关问题。
135 20
|
7月前
|
Go
go语言for遍历映射(map)
go语言for遍历映射(map)
215 12