setmat在c语言中是什么意思,C语言之set用法

下面简单总结下set容器的操作:

1、set对象的定义和初始化

set对象的定义和初始化方法包括:

sets;

sets(s1);

sets(b, e);

其中,b和e分别为迭代器的开始和结束的标记。

例如:

#include #include #include using namespace std;

int main(){

vectorv;

for (int i = 0; i < 10; i++){

v.push_back(i);

v.push_back(i);

}

sets(v.begin(), v.end());

printf("%d\n", v.size());

printf("%d\n", s.size());

return 0;

}

注意:键是不能重复的。

2、set中数据的插入

与map不同,set中数据只能通过insert()函数进行插入。

例如:

#include #include #include using namespace std;

int main(){

vectorv;

for (int i = 0; i < 10; i++){

v.push_back(i);

v.push_back(i);

}

sets;

s.insert(v.begin(), v.end());

set::iterator it;

for (it = s.begin(); it != s.end(); it++){

printf("%d\t", *it);

}

printf("\n");

s.insert(10);

for (it = s.begin(); it != s.end(); it++){

printf("%d\t", *it);

}

printf("\n");

return 0;

}

3、从set中查找和读取元素

从set中查找同样可以使用count()函数和find()函数,两者的区别在之前的map中已经总结。

例如:

#include #include #include using namespace std;

int main(){

vectorv;

for (int i = 0; i < 10; i++){

v.push_back(i);

v.push_back(i);

}

sets;

s.insert(v.begin(), v.end());

set::iterator it;

for (it = s.begin(); it != s.end(); it++){

printf("%d\t", *it);

}

printf("\n");

printf("%d\n", s.count(9));

printf("%d\n", *(s.find(9)));

return 0;

}

4、从set中删除元素

从set中删除元素使用到的函数是erase()函数,主要有以下的几种形式:

erase(k);

erase(p);

erase(b, e);

其中,p表示的迭代器指向的元素,b和e分别是迭代器的开始和结束。

例如:

#include #include #include using namespace std;

int main(){

vectorv;

for (int i = 0; i < 10; i++){

v.push_back(i);

v.push_back(i);

}

sets(v.begin(), v.end());

set::iterator it;

for (it = s.begin(); it != s.end(); it++){

if (*it == 5){

break;

}

}

s.erase(it, s.end());

set::iterator it_1;

for (it_1 = s.begin(); it_1 != s.end(); it_1++){

printf("%d\t", *it_1);

}

printf("\n");

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值