【c++】vector容器&set容器的基本操作

2023-10-27

vector顺序存储, 动态开辟空间,当需要实现拉链发的hash很方便而且也可以用作邻接表存图。
常用方法:push_back(), pop_back(), size(), clear(), insert(), erase();
其中:erase()可以删除单个元素,也可以删除一个区间的元素.erase(it)it为迭代器。
erase(first, last)即删除[first, last)内的元素。比如V.erase(V.begin()+1, V.end())

#include <iostream>
#include <vector>
#include <cstdio>
#include <vector>
using namespace std;
void travelMethodFirst(vector<int> myVector);
void travleMethodSecond(vector<int> myVector);
void deleteElementMethodFirst(vector<int>& myVector, int index);
void deleteElementMethodSecod(vector<int>& myVector, int from, int to);
void deleteLastElement(vector<int>& myVector);
void insertElement(vector<int> &myVector, int pos, int element);
int main()
{
    vector<int> V;
    //增加
    for(int i = 0;i < 10; i++) {
        V.push_back(i);
    }
    travleMethodSecond(V);
    //删除第三个元素
    vector<int>::iterator it = V.begin();
    deleteElementMethodFirst(V, 3);
    travleMethodSecond(V);
    deleteElementMethodSecod(V, 6, 9);
    travelMethodFirst(V);
    deleteLastElement(V);
    travleMethodSecond(V);
    V.clear();
    for(int i = 0;i < 10; i++) {
        V.push_back(i);
    }
    travelMethodFirst(V);
    insertElement(V, 2, 100);
    travelMethodFirst(V);
    return 0;
}
//在下标为pos的位置插入一个元素.
void insertElement(vector<int> &myVector, int pos, int element) {
    if(myVector.size() > (unsigned)pos) {
        myVector.insert(myVector.begin()+pos, element);
    }
}

//根据下标删除元素并且删除单个元素
void deleteElementMethodFirst(vector<int>& myVector, int index) {
    if(myVector.size() > (unsigned)index) {
        vector<int>::iterator it = myVector.begin();
        myVector.erase(it + index);
    }
}
//根据下标删除元素并且删除一个区间的元素[from, to)
void deleteElementMethodSecod(vector<int>& myVector, int from, int to) {
    if(from > to) {
        swap(from, to);
    }
    if((unsigned)to <= myVector.size()) {
        vector<int>::iterator it = myVector.begin();
        myVector.erase(it+from, it+to);
        //myVector.erase((myVector.begin()+from, myVector.begin()+to));
    }
}
//删除最后一个元素
void deleteLastElement(vector<int>& myVector) {
    if(!myVector.empty()) {
        myVector.pop_back();
    }
}

//下标方式访问
void travelMethodFirst(vector<int> myVector) {
    for(unsigned i = 0; i < myVector.size(); i++) {
        cout << myVector[i] << "  ";
    }
    cout << endl;
}
//指针方式访问
void travleMethodSecond(vector<int> myVector) {
    vector<int>::iterator it = myVector.begin();
    for(unsigned i = 0; i < myVector.size(); i++) {
        printf("%d  ",  *(it+i));
    }
    cout << endl;
}

set是一个内部自动有序且不含重复元素的容器。主要作用是自动去重并按升序排序。
如果自定义结构体,需要比较函数。
注意:set只能通过迭代器(iterator)访问, set::iterator it;
而且可以通过it访问set的元素,由于除vector和string之外的STL容器都不支持 (it+i)的访问方式。
常用方法:insert(), find(), erase(), size(), clear();
其中:erase()有两种:对于set st;可以用st.erase(value)或者st.erase(it)it为迭代器。

#include <iostream>
#include <cstdio>
#include <set>
using namespace std;

struct info {
    int value;
    string str;
    info(int val, string mystr) {
        value = val;
        str = mystr;
    }
    info() {}
    bool operator < (const info &a) const {
        if(a.value != value) {
            return a.value > value;
        } else {
            return a.str > str;
        }
    }
};

//输出
void output(set<info> mySet) {
    set<info>::iterator it = mySet.begin();
    for(; it != mySet.end(); it++) {
        cout << it->value << " " << it->str << endl;
    }
}
//查找
void testFindMethod(set<info>& myInfoSet, info tmp) {
    set<info>::iterator it = myInfoSet.find(tmp);
    if(it != myInfoSet.end()) {
        cout << "查找结果: " << it->value << " " << it->str << endl;
    }
}
//查找并删除
void testDeleteMethodOne(set<info>& myInfoSet, info tmp) {
     set<info>::iterator it = myInfoSet.find(tmp);
    if(it != myInfoSet.end()) {
        cout << "查找结果: " << it->value << " " << it->str << endl;
        myInfoSet.erase(it);
       // myInfoSet.erase(tmp);
        cout << "*****删除后的结果*****" << endl;
        output(myInfoSet);
    }
}
//删除一个区间内的元素
void testDeleteMethodTwo(set<info>& myInfoSet, info tmp) {
    set<info>::iterator it = myInfoSet.find(tmp);
    cout << "删除前:"  << endl;
    output(myInfoSet);
    if(it != myInfoSet.end()) {
        myInfoSet.erase(it, myInfoSet.end());
    }
    cout << "删除后:"  << endl;
    output(myInfoSet);

}

//测试
int main()
{
    set<info> myInfoSet;
    info read;
    read.value = 100;
    read.str = "alibaba";
    myInfoSet.insert(read);
    read.value = 10;
    read.str = "baidu";
    myInfoSet.insert(read);
    read.value = 10;
    read.str = "baidux";
    myInfoSet.insert(read);
    read.value = 20;
    read.str = "jd";
    myInfoSet.insert(read);
     read.value = 30;
    read.str = "huawei";
    myInfoSet.insert(read);
    cout << myInfoSet.size() << endl;
    output(myInfoSet);

    info tmp(10, "baidu");
    testFindMethod(myInfoSet, tmp);
    testDeleteMethodOne(myInfoSet, tmp);
    info temp(30, "huawei");
    testDeleteMethodTwo(myInfoSet, temp);
    return 0;
}

#include< bits/stdc++.h> 包含的头文件。
目前国内oj中,poj,hdu 不支持这个函数,这几个oj的编译器问题,其他国外的oj,还有台湾的oj都支持,CF,Topcoder也都支持。

// C++ includes used for precompiling -*- C++ -*-

// Copyright (C) 2003-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file stdc++.h
 *  This is an implementation file for a precompiled header.
 */

// 17.4.1.2 Headers

// C
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdalign>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【c++】vector容器&set容器的基本操作 的相关文章

  • Kafka框架学习笔记 尚硅谷

    Kafka框架学习笔记 尚硅谷 因为本人不是大数据方向的 但是公司一个项目用到了kafka 我就学习一下 如果笔记有什么不对的地方 敬请谅解 文章目录 Kafka框架学习笔记 尚硅谷 因为本人不是大数据方向的 但是公司一个项目用到了kafk
  • 深圳市人力资源和社会保障局关于用人单位招用就业困难人员申请补贴和奖励有关事项的通知

    各有关单位 为鼓励用人单位招用就业困难人员 促进困难群体就业 根据 深圳市人民政府关于进一步完善就业援助政策的通知 深府 2013 60号 深圳市人民政府关于做好当前和今后一段时期就业创业工作的实施意见 深府规 2017 12号 有关规定
  • android 异步加载图片缩略图

    建一个AsyncLoadedImage类继承AsyncTask异步加载类 调用publishProgress方法更新onProgressUpdate贮存缩略图信息到Adapter 监听Adapter Change实现异步加载缩略图 main
  • Go基础(复杂类型):函数的闭包

    函数的闭包 Go 函数可以是一个闭包 闭包是一个函数值 它引用了其函数体之外的变量 该函数可以访问并赋予其引用的变量的值 换句话说 该函数被 绑定 在了这些变量上 例如 函数 adder 返回一个闭包 每个闭包都被绑定在其各自的 sum 变
  • OpenCV快速傅里叶变换(FFT)用于图像和视讯流的模糊检测

    OpenCV快速傅里叶变换 FFT 用于图像和视频流的模糊检测 翻译自 OpenCV Fast Fourier Transform FFT for blur detection in images and video streams 原文链
  • PHP实现一个简单的登录和注册,以及实现方法和页面

    下面是一个简单的PHP代码示例 实现了登录和注册功能 首先 创建一个名为index php的文件 用于显示登录和注册表单 h2 登录 h2
  • Linux 安装JDK17

    1 官网下载JDK17 这里我们下载的是 x64 Compressed Archive版本 2 解压tar 文件 进入文件下载目录 自己定义 我这里都放在software cd usr local softwar 解压tar文件 tar v
  • 【毕业项目】自主设计HTTP

    博客介绍 运用之前学过的各种知识 自己独立做出一个HTTP服务器 自主设计WEB服务器 背景 目标 描述 技术特点 项目定位 开发环境 WWW介绍 网络协议栈介绍 网络协议栈整体 网络协议栈细节 与http相关的重要协议 HTTP背景知识补
  • 最强自动化测试框架Playwright(11)- 录制视频

    视频 使用playwright 您可以录制测试视频 录制视频 视频在测试结束时在浏览器上下文关闭时保存 如果手动创建浏览器上下文 请确保等待 browser context close context browser new context
  • 分布式任务调度可选方案

    1 除了基于jvm的java之处 新接触一个JVM语言 SCALA 一种同时面向脚本和面向函数的语言 spark大数据框架是基于scala语言 照着网络教程 简单的写了几个例子 感觉object class与java语境中还是有一定的差异
  • 2023美赛F题完整数据代码模型成品文章思路-- Green GDP

    论文摘要 模型和其他部分内容如下 摘要 现行的以GDP为核心的国民经济核算体系 由于忽略非市场产出 环境破坏 资源浪费方面的有关计算 这样的指标并不完整 由于经济活动中 对资源消耗和对环境的负面影响越来越大 而长期忽略这种负面影响的后果 高
  • Hexo在多台电脑上提交和更新

    文章目录 1 博客搭建 2 创建一个新文件夹new 用于上传hexo博客目录 3 github上创建hexo分支并设置为默认分支 创建hexo分支 将hexo分支设置为默认分支 4 进入新建的文件夹中git clone 再上传相关文件至he
  • navicat for mysql 连接 mysql 出现1251错误

    navicat for mysql下载地址 链接 https pan baidu com s 1Nh2ippFKHrWXnzPx hda8g 密码 fumf 客户端使用navicat for mysql 本地安装了mysql 8 0 但是在
  • CVE-2023-35843:NocoDB任意文件读取漏洞复现

    文章目录 NocoDB 存在任意文件读取漏洞CVE 2023 35843 0x01 前言 0x02 漏洞描述 0x03 影响范围 0x04 漏洞环境 0x05 漏洞复现 1 访问漏洞环境 2 构造POC 3 复现 0x06修复建议 Noco
  • zookeeper选举流程源码分析

    zookeeper选举流程源码分析 选举的代码主要是在QuorumPeer java这个类中 它有一个内部枚举类 用来表示当前节点的状态 public enum ServerState LOOKING FOLLOWING LEADING O
  • 关于vue项目的node、node-sass、sass-loader的版本问题

    后续博客全部搬迁至个人博客 欢迎访问 最近遇到一个问题 在下载vue项目的node modules的包时 node sass和sass loader版本总是不匹配 当两者匹配时 node和node sass版本又不匹配 导致我的服务一直起不
  • 简历中场景

    场景一 消息的发送 接收 利用rabbitmq的单通道模式 实现专家端发送消息 老师端监听消息 流程 subject accept server中producer消息 mq message中consumer监听消息 并保存在数据库中 调用m
  • 安装potobuf(make check通过)

    很多文章中给出的方法是在github上下载项目 然后创建build再安装googletest 但是在最后的make check时一直报错 如果是python中使用 直接sudo pip3 install i https pypi tuna
  • Spring 3整合Quartz 2实现定时任务一:常规整合

    最近工作中需要用到定时任务的功能 虽然Spring3也自带了一个轻量级的定时任务实现 但感觉不够灵活 功能也不够强大 在考虑之后 决定整合更为专业的Quartz来实现定时任务功能 首先 当然是添加依赖的jar文件 我的项目是maven管理的

随机推荐

  • Cannot run program “D:\Environment\jdk1.8\bin\java.exe”解决方法

    Cannot run program D Environment jdk1 8 bin java exe in directory D Project Java Idea project docker springboot CreatePr
  • Scratch的广播与消息

    在事件积木中 有一块触发积木叫当接收到 消息1 对应地 有两块积木 广播 消息1 广播 消息1 并等待 广播 消息机制就是编程中的全局事件 当一个消息被广播时 所有角色 包含广播者自身 都会接收到该消息 只要一个角色有该消息的接收脚本 即可
  • 【Linux】进程程序替换 &&简易mini_shell实现

    文章目录 替换原理 替换函数 替换函数的使用 简易shell实现程序 替换原理 目前 我们使用fork创建子进程 为了用if else让子进程执行父进程代码的一部分 如果想让子进程执行一个全新的程序 进程不变 仅仅替换当前进程的代码和数据
  • python怎么自学

    其实0基础选择python学习入行的不在少数 Python近段时间一直涨势迅猛 在各大编程排行榜中崭露头角 得益于它多功能性和简单易上手的特性 让它可以在很多不同的工作中发挥重大作用 正因如此 目前几乎所有大中型互联网企业都在使用 Pyth
  • 图像识别(九)

    大家好啊 我是董董灿 很多同学在做深度学习时 都会遇到难以理解的算法 SoftMax肯定是其中一个 初学者大都对它一知半解 只知道SoftMax可以用来做分类 输出属于某个类别的概率 但是 为什么要用SoftMax呢 这个算法又是如何将神经
  • javascript原型、原型链、继承详解

    一 原型和原型链的基本概念 在JavaScript中 每个对象都有一个原型对象 prototype 原型对象就是一个普通的对象 在创建新对象时 可以将该对象作为新对象的原型 原型对象可以包含共享的属性和方法 这些属性和方法可以被新对象继承和
  • ajax异步加载和cmd,异步传输Ajax(JQ)

    异步传输Ajax JQ JSP 服务器 Stringstr name a 张三 a 李四 age 18 resp getWriter write str 客户端 function button eq 0 click function aja
  • 基于组合优化的3D家居布局生成看千禧七大数学难题之NP问题

    本文探讨了运筹学和组合优化方法在3D家居布局生成中的应用 并调研了AI生成3D场景布局的最新方法 文中结合了家居家装业务的实际应用场景 从算法建模和计算复杂度的角度上阐述了室内设计的布局问题中存在的难点 以及如何用简化和近似的思想来建模3D
  • PhpStorm PHP代码注释自动插入设置

    设置路径 PhpStorm gt Prererences gt File and Code Templates 如下图 PHP 类注释 PHP Class Doc Comment CARET package NAMESPACE class
  • go使用mongodb

    何为MongoDB 简介 MongoDB 是由C 语言编写的 是一个基于分布式文件存储的开源数据库系统 在高负载的情况下 添加更多的节点 可以保证服务器性能 MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案 MongoDB
  • python文档处理脚本 github_使用 Python3 编写 Github 自动周报生成器

    简介 都说好东西要分享出去 但这个项目例外 我们将教你使用 PyGithub 自动生成周报 千万不要让人知道你学了这个项目 否则你将承包全公司人的周报 每个程序员都有一个痛 那就是周报 每次写周报的时候 都感觉身体被掏空 我这周TM都干了什
  • C++一定要为类提供拷贝构造函数的情况

    在C 类中存在成员指针并且在类中为该指针动态申请内存 且该类的对象可能作为函数的形参时 是一定要提供拷贝构造函数的 防止前拷贝直接将该指针拷贝走 test cpp 定义控制台应用程序的入口点 include stdafx h include
  • 测试CUDA的samples

    测试CUDA的samples 1 cd usr local cuda 8 0 samples 1 Utilities deviceQuery 2 sudo make 3 sudo deviceQuery
  • 【从零开始学习深度学习】41. 算法优化之RMSProp算法【基于AdaGrad算法的改进】介绍及其Pytorch实现

    上一篇文章AdaGrad算法中提到 因为调整学习率时分母上的变量 s t boldsymbol s t st 一直在累加按元素平方的小批量随机梯度 所以目标函数自变量每个元素的学习率在迭代过程中一直在降低 或不变 因此 当学习率在迭代早期降
  • python关于onnx模型的一些基本操作

    onnx的基本操作 一 onnx的配置环境 二 获取onnx模型的输出层 三 获取中节点输出数据 四 onnx前向InferenceSession的使用 1 创建实例 源码分析 2 模型推理run 源码分析 五 遇到的一些问题 最近在对模型
  • 如何用Socket和Wsgiref实现一个Web服务器

    目录 1 用Socket实现一个简单的web服务器 2 用Wsgi实现一个简单的web服务器 3 用Wsgi实现支持多url的web服务器 三 用Wsgi实现支持多url和图片的web服务器 1 用Socket实现一个简单的web服务器 首
  • Python爬虫入门续(3):获取2022年10月CSDN文章版本格式的评论数

    一 引言 好久没上CSDN备份及获取文章数据 今天用原有的代码进行CSDN自己博文数据的备份 获取文章点赞数 评论数 阅读数等数据时 发现程序报错 经过仔细分析 发现是CSDN的评论数据展示格式发生了变化 二 报文格式变化对比 原来的CSD
  • TCP/IP 网络编程(一):基础知识

    声明 本系列文章参考书 TCPIP网络编程 韩 尹圣雨 本人仅作笔记使用 目录 一 网络编程和套接字 二 Linux文件操作 文件描述符 打开文件 关闭文件 将数据写入文件 读取文件中的数据 三 套接字类型与协议设置 协议 计算机间对话需遵
  • ThreadPoolExecutor线程池解析与BlockingQueue的三种实现

    目的 主要介绍ThreadPoolExecutor的用法 和较浅显的认识 场景的使用方案等等 比较忙碌 如果有错误还请大家指出 ThreadPoolExecutor介绍 ThreadPoolExecutor的完整构造方法的签名如下 Thre
  • 【c++】vector容器&set容器的基本操作

    vector顺序存储 动态开辟空间 当需要实现拉链发的hash很方便而且也可以用作邻接表存图 常用方法 push back pop back size clear insert erase 其中 erase 可以删除单个元素 也可以删除一个