STL-vector+题目

vector-顺序表,可以存放任意类型的数据。

vector在 和迭代器、范围for方面的使用差不多一样。

vector的迭代器有普通的还有const类型的迭代器。

vector使用下标+ 好用。迭代器是容器通用的访问方式,使用方法基本相似。

cpp 复制代码
#include <iostream>
#include <vector>

template<class T>
void PrintVector(const vector<T>& v)
{
	vector<T>::const_iterator cit = v.begin();
	while(cit != v.end())
	{
		cout << *cit << " ";
		++cit;
	}
	cout << endl;
}
int main ()
{
	// 最常见的构造方式是前两个
	std::vector<int> v1;                                // 一个整型顺序表
	std::vector<int> v2(4, 100);                       // 4个100初始化
	std::vector<int> v3(v2.begin(),v2.end());  // 迭代器区间初始化
	std::vector<int> v4(v3);                       // 拷贝构造用v3构造v4
	std::vector<char> v5(4, 'x');
	PrintVector(v2); //有模板自动获取类型
	PrintVector(v5);
	
	std::vector<string> v6;
	std::string s1("ggg");
	v6.push_back(s1);
	v6.push_back(string("zhende"));
	v6.push_back("nb");
	PrintVector(v6);
	
	// auto it = v1.begin(); 
	vector<int>::iterator it = v1.begin(); //可以利用迭代器修改内容 
	vector<int>::const_iterator cit = v1.begin(); //不能利用迭代器修改内容
}

只出现一次的数字

给你一个 非空 整数数组 nums ,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

你必须设计并实现线性时间复杂度的算法来解决此问题,且该算法只使用常量额外空间。

示例 1 :

输入:nums = 2,2,1 输出:1

示例 2 :

输入:nums = 4,1,2,1,2 输出:4

示例 3 :

输入:nums = 1 输出:1

cpp 复制代码
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int val = 0;
        for(auto e : nums) //直接异或,把出现了两次的数字一异或就没了。
        {
            val ^= e;
        }
        return val;
    }
};
相关推荐
dsyyyyy11016 小时前
JavaScript变量
开发语言·javascript·ecmascript
玖玥拾7 小时前
C/C++ 基础笔记(十三)继承
c语言·c++·继承
z落落7 小时前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway27 小时前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446237 小时前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了8 小时前
安装git bash选项推荐
开发语言·git·bash
ct9788 小时前
React 状态管理方案深度对比
开发语言·前端·react
ao-weilai8 小时前
C++:哈希表
c++·哈希算法·散列表
数量技术宅8 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
汉克老师8 小时前
GESP7级C++考试语法知识(二、指数函数(1、pow() 函数)
c++·指数函数·pow·gesp7级·精度误差