关闭

C++学习笔记

178人阅读 评论(0) 收藏 举报
分类:

一、删除容器中指定元素用法:

1.vector使用方法:

vector<int> vec;
vec.push_back(1); vec.push_back(9); vec.push_back(0);
vector< int>::iterator iter;
for (iter = vec.begin(); iter != vec.end();) //for循-环??中D不?要?ait++
{
	if (*iter == 9)
	{
		iter = vec.erase(iter );
	}
	else
	{
		++iter ;
	}
}
for (iter = vec.begin(); iter != vec.end();iter ++)
{
    cout<< "删除指定元素后:" <<*iter <<endl;
}

<span style="color:#000000;">Vector<Sprite*>vecStar;
Vector<Sprite*>::iterator iter;
//加入2个精灵
vecStar.pushBack(m_pStar1);
vecStar.pushBack(m_pStar2);
//隐藏精灵:
for( auto& iter : vecStar)
    {
        iter->setVisible(false);
    }
//显示一定数量的精灵:
    int nNum = 0;
    for (iter = vecStar.begin(); iter != vecStar.end(); iter++)
    {
        nNum++;
        if (nNum<=nStar) {
            Sprite* sprite = *iter;
            sprite->setVisible(true);
        }
    }</span>


2.map使用方法:
#include <iostream>
#include <map> 
#include <string>

map<string,int> mapT; 
map<string,int>::iterator iter;
mapT["A"]=1;  mapT["B"]=2;  mapT["C"]=3;
for (iter=mapT.begin();iter!=mapT.end();)
{
	if (iter->second==2){  //second表第2个参数
		iter=mapT.erase(iter);
	}
	else
	{
		++iter;
	}
}
for (iter=mapT.begin();iter!=mapT.end();iter++)
{
	cout<<iter->second<<endl;
}
3.list使用方法:
list<int> ListTest;
	ListTest.push_back(1);
	ListTest.push_back(2);
	ListTest.push_back(3);
	list<int>::iterator iter;
	for (iter=ListTest.begin();iter!=ListTest.end();)
	{
		if (*iter==2)
		{
			iter=ListTest.erase(iter);
		}
		else{
			++iter;
		}
	}

二、随机数:
int MAX = 10; //不包括10
	srand((unsigned)time(0));
	for (int i = 0; i != 100; ++i)
	{
		printf("随机值:%d\n" ,rand()%MAX);
	}

三、字符串:
1.逆序输出字符串:
string str;
    cin>>str;
    int len = str.length();
    while (len>0) {
        cout<<str[--len];
    }
2.筛选数字:
string str;
    cin>>str;
    int len = str.length();
    for(int i=0;i<len;i++)
    {
        if(str[i]>='0'&&str[i]<='9')
        {
            cout<<str[i];
        }
    }







































0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场