STL删除元素

时间:2023-12-30 21:23:26

1、从vector中删除多个元素:

#include <iostream>
#include <vector> int main()
{
std::vector<int> vect;
for(int i = ; i <= ; i++)
{
vect.push_back(i);
} ///*
int size = vect.size();
for(unsigned int i = ; i < size;)
{
if(vect[i] % == )
{
vect.erase(vect.begin() + i);
size--;
}
else
{
i++;
}
}
//*/
/*
auto it = vect.begin();
while(it != vect.end())
{
if(*it % 2 == 1)
{
vect.erase(it);
}
else
{
it++;
}
}
*/ for(auto& item : vect)
{
std::cout<<"item:"<<item<<std::endl;
}
int main()
{
std::vector<int> vect;
for(int i = ; i <= ; i++)
{
vect.push_back(i);
} ///*
int size = vect.size();
for(unsigned int i = ; i < size;)
{
if(vect[i] % == )
{
vect.erase(vect.begin() + i);
size--;
}
else
{
i++;
}
}
//*/
/*
auto it = vect.begin();
while(it != vect.end())
{
if(*it % 2 == 1)
{
vect.erase(it);
}
else
{
it++;
}
}
*/ for(auto& item : vect)
{
std::cout<<"item:"<<item<<std::endl;
}
}

std::vector可以越界访问,如以下代码会输出0,而不会抛出异常。应该是由vector建立时的容量决定的。

#include <iostream>
#include <vector> int main()
{
std::vector<int> vect;
vect.push_back();
vect.push_back();
std::cout<<vect[]<<std::endl;
}

定义一个返回引用的函数,但如果接收的类型没有定义为引用类型,则仍会是复制,auto也是复制。如下:

#include <iostream>
#include <vector> class Test
{
Test(){};
public:
static Test& Instance()
{
static Test _instance;
return _instance;
}
std::vector<int>& get_vect()
{
return vect;
} std::vector<int> vect;
}; int main()
{
Test::Instance().vect.push_back();
Test::Instance().vect.push_back(); std::vector<int> vect = Test::Instance().get_vect(); //复制
//std::vector<int>& vect = Test::Instance().get_vect(); //引用 vect.push_back();
vect.push_back(); for(auto item : Test::Instance().vect)
{
std::cout<<item<<std::endl;
}
}