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;
    }
};
相关推荐
端平入洛18 小时前
auto有时不auto
c++
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月2 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost