• STL在迭代的过程,删除指定的元素


    直接在Code。在 Picture

    #include <iostream>
    #include <list>
    
    using namespace std;
    
    // STL在迭代的过程中,删除指定的元素
    int main()
    {
    	list<int> listTest;
    
    	listTest.push_back(-1);
    	listTest.push_back(-1);
    	listTest.push_back(-1);
    	listTest.push_back(-1);
    
    	cout<<"list size: "<<listTest.size()<<endl;
    
    	list<int>::iterator itList;
    
    	for (itList=listTest.begin(); itList != listTest.end(); /*no itList++ !!*/ )
    	{
    		cout<<"data: "<<*itList<<endl;
    
    		// 第一种方法
    		if (*itList <= 0)
    			itList = listTest.erase(itList);
    		else
    			++itList;
    	}
    	cout<<"list size: "<<listTest.size()<<endl;
    	cout<<"======================================"<<endl;
    
    
    	listTest.push_back(-1);
    	listTest.push_back(-1);
    	listTest.push_back(-1);
    	listTest.push_back(1);
    
    	cout<<"list size: "<<listTest.size()<<endl;
    	
    	for (itList=listTest.begin(); itList != listTest.end(); ++itList)
    	{
    		cout<<"data: "<<*itList<<endl;
    
    		// 另外一种方法
    		if (*itList <= 0)
    			*itList = 0;		// 做个记录标志。等待迭代完进行回收
    	}
    
    	listTest.remove(0);			// 回收 0
    
    	cout<<"list size: "<<listTest.size()<<endl;
    	cout<<"======================================"<<endl;
    
    	return 0;
    
    }
    

    执行结果:


    版权声明:本文博主原创文章。博客,未经同意,不得转载。 http://blog.csdn.net/core__code

  • 相关阅读:
    CodeForce 677C
    1A -- Theatre Square
    CodeForce 677B Vanya and Food Processor
    CodeForce 680C Bear and Prime 100
    1B -- Spread sheet
    socket.io 推送
    网站性能测试
    openlayers/// Puppeteer.js
    div 光标处插入内容
    emjoi 表情
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4758281.html
Copyright © 2020-2023  润新知