【cpp--->vector】

文章详细介绍了C++标准库中的vector容器,包括构造、容量控制、访问、修改、比较等主要接口的使用方法,并提供了杨辉三角和电话号码字母组合的实战示例。此外,还讨论了vector类的模拟实现及其难点,如数据移动、插入删除操作的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、vector主要接口介绍

1.构造

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	//默认构造一个容器为空的对象,没有元素
	vector<int> v1;

	//用n个元素构造一个对象,val默认为T()
	vector<int> v2(3);
	vector<int> v3(3, 10);

	//用任意类型的迭代器区间构造一个对象
	string s("hello world");
	vector<char> v4(s.begin(), s.end() - 1);

	//拷贝构造
	vector<char> v5(v4);

	return 0;
}

在这里插入图片描述

2.容量控制

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int> v1(10, 1);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;

	//开空间加初始化,可以增加数据可以删减数据
	v1.resize(11, 2);
	cout << "v1.size(): " << v1.size() <<" " << "v1.capacity(): " << v1.capacity() << endl;
	for (auto e : v1)
	{
		cout << e << " ";
	}
	cout << endl;
	//删减数据
	v1.resize(10);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	for (auto e : v1)
	{
		cout << e << " ";
	}
	cout << endl;
	//扩容,小于当前容量不处理
	v1.reserve(11);
	cout << "v1.size(): " << v1.size() << " " <<"v1.capacity(): " << v1.capacity() << endl;
	v1.reserve(100);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	//缩容,缩容至等于size的大小
	v1.shrink_to_fit();
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	
	return 0;
}

在这里插入图片描述

3.访问

#include<iostream>
#include<vector>
using namespace std;
void  func(const vector<int>& v)
{
	cout << typeid(v[0]).name() << endl;
}
int main()
{
	int arr[] = { 3,4,5,6,8,7,6,8,7,11,13,15 };
	vector<int> v1(arr,arr+sizeof(arr)/sizeof(arr[0]));
	//访问队头和队尾数据
	cout << " v1.back(): " << v1.back() << endl;
	cout <<" v1.front(): " << v1.front()<< endl;
	//[]重载,返回val的引用,有普通val,也有const val
	cout << "++ : ";
	for (int i = 0; i < v1.size(); i++)
	{
		cout << ++v1[i] << " ";
	}
	cout << endl;
	//const val
	func(v1);
	return 0;
}

在这里插入图片描述

4.修改

1.尾插和尾删

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int> v1;
	//尾插和尾删
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(4);
	for (auto e : v1)
	{
		cout << e;
	}
	cout << endl;
	//尾删
	v1.pop_back();
	for (auto e : v1)
	{
		cout << e;
	}
	cout << endl;
	return 0;
}

在这里插入图片描述

2.任意位置插入和删除

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	string s("hello world");
	vector<char> v1(s.begin(),s.end());
	
	//任意迭代器位置插入一个val,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 4, ' ');

	//任意迭代器位置插入n个val,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 6, 3, 'x');

	//任意迭代器位置插入任意类型的迭代器区间,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 9, s.begin(), s.end());
	
	//删除任意位置的一个val,返回删除位置的下一个位置的迭代器位置
	v1.erase(v1.begin() + 4);

	//删除任意迭代器区间,返回删除位置的下一个位置的迭代器位置
	v1.erase(v1.begin() + 5, v1.end() - 6);
	return 0;
}

在这里插入图片描述

5.比较

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main()
{
	vector<string> v1 = {"hello"};
	vector<string> v2{"world"};
	cout << (v1 == v2) << endl;
	cout << (v1 < v2) << endl;
	cout << (v1 <= v2) << endl;
	cout << (v1 > v2) << endl;
	cout << (v1 >= v2) << endl;
	return 0;
}

在这里插入图片描述

二、vector接口实战应用

1.杨辉三角

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> vv(numRows);
        //给vector中的vector开空间并初始化
        for(int i=0;i<numRows;i++)
        {
            vv[i].resize(i+1,1);
        }
        //计算杨慧三角
        for(int i=2;i<numRows;i++)
        {
            for(int j=1;j<vv[i].size()-1;j++)
            {
                vv[i][j]=vv[i-1][j-1]+vv[i-1][j];
            }
        }
        return vv;
    }
};

2.电话号码的字母组合

vector<string> vstr{{},{},{"abc"},{"def"},{"ghi"},{"jkl"},{"mno"},{"pqrs"},{"tuv"},{"wxyz"}};
class Solution {
public:
    void _letterCombinations(const string& digits,int id
    ,string combinations,vector<string>& result)
    {
        //digits中的数字读完则记录组合并返回
        if(id==digits.size())
        {
            result.push_back(combinations);
            return;
        }
        //将digits中的数字字符转整型
        int vstrId=digits[id]-'0';
        //遍历记录一个数字对应按键中的所有字母
        for(auto e: vstr[vstrId])
        {
            //全排列digits中所有数字的对应按键中的字母,排列一组临时记录在combinations
            //记录到最后一个按键的字母就传递给result,然后重头开始记录。
            _letterCombinations(digits,id+1,combinations+e,result);
        }
    }
    vector<string> letterCombinations(string digits) {
        //没有按按键的时候返回空数组
        if(digits.size()==0)
        {
            return vector<string>();
        }
        //记录结果
        vector<string> result;
        //临时记录组合
        string combinations;
        _letterCombinations(digits,0,combinations,result);
        return result;
    }
};

三、vector类模拟实现

1.实现难点

在构造实现过程中使用push_back或者reserve这些接口需要初始化成员变量,赋值构造和拷贝构造的数据拷贝应避免深层次的浅拷贝,不能用内存拷贝这些接口直接拷贝,因为有可能start存储的是自定义类型。

任意位置的插入和删除都需要用到pos,pos在insert扩容后是失效的,因为扩容后start地址发生变化,之前的pos是根据没改变时候的start确定的地址。所以pos需要在扩容前记录相对位置,扩容后根据相对位置找到当前位置。删除后pos也是失效的,因为pos如果是finish的前一个数据,再访问pos就越界访问了。

在数据移动的时候,需要特别注意控制end的访问区间,end不能访问没有开辟的空间,也就是不能方位>=end_of_storage的空间。

2.代码实现

#pragma once
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
namespace kk
{
	template <class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;
	public:
		//begin
		iterator begin()
		{
			return _start;
		}
		//end
		iterator end()
		{
			return _finish;
		}
		// const_begin
		const_iterator begin()const
		{
			return _start;
		}
		// const_end
		const_iterator end()const
		{
			return _finish;
		}
		//构造
		vector()
			:_start(nullptr)
			, _finish(nullptr)
			, _end_of_storage(nullptr)
		{}
		//拷贝构造
		vector(const vector<T>& v)
		{
			_start = new T[v.capacity()];
			if (v._start)
			{
				//vector内部可能存储的是自定义类型比如string,直接使用
				//内存拷贝会曹成深层次的浅拷贝问题,对象内部的str地址相同
				//所以需要使用自定义类型的复制构造。
				for (int i = 0; i < v.size(); i++)
				{
					*(_start+i) = *(v._start+i);
				}
			}
			_finish = _start+v.size();
			_end_of_storage = _start+v.capacity();
		}
		vector(const T& val)
		{
			reserve(4);
			*_start = val;
			_finish = _start + 1;
		}
		vector(size_t n,const T& val = T())
		{
			reserve(n);
			for (int i = 0; i < n; i++)
			{
				push_back(val);
			}
		}
		//赋值构造
		vector<T>& operator=(vector<T> v)
		{
			std::swap(_start, v._start);
			std::swap(_finish, v._finish);
			std::swap(_end_of_storage, v._end_of_storage);
			return *this;
		}
		// 扩容
		void resize(size_t n, const T& val = T())
		{
			//小于数据长度
			if (n < size())
			{
				//直接调整finish的位置
				_finish = _start + n;
			}
			//大于数据长度
			else
			{
				//扩容
				if (n > capacity())
				{
					reserve(n);
				}
				//初始化多余的空间,更新_finish
				while (_finish != _start + n)
				{
					*_finish = val;
					++_finish;
				}
			}
		}
		// 扩容加初始化
		void reserve(size_t n)
		{
			if (n > capacity())
			{
				//开新空间
				iterator tmp = new T[n];
				//使用赋值拷贝将原来的数据拷贝至新开空间
				for (int i = 0; i < size(); i++)
				{
					*(tmp + i) = *(_start + i);
				}
				//_start一旦改变就求不出数据长度了,所以提前记录
				size_t len = size();
				//释放旧空间
				delete[] _start;
				//更新成员位置
				_start = tmp;
				_finish = _start + len;
				_end_of_storage = _start + n;
			}
		}
		//尾插
		void push_back(const T& val )
		{
			insert(end(), val);
		}
		//尾插
		void pop_back()
		{
			erase(end());
		}
		//任意位置插入
		iterator insert(iterator pos, const T& val)
		{
			//断言pos位置
			assert(pos >= begin() && pos <= end());
			//扩容
			if (size() + 1 > capacity())
			{
				size_t len = pos - _start;
				reserve(capacity() == 0 ? 4 : capacity() * 2);
				pos = _start + len;
			}
			//移动数据
			iterator end = _finish;
			while (end != pos)
			{
				*end = *(end-1);
				end--;
			}
			//插入数据更新finish
			*pos = val;
			_finish++;
			return pos;
		}
		iterator insert(iterator pos,size_t n,const T& val)
		{
			//断言pos位置
			assert(pos >= begin() && pos <= end());
			//扩容
			if (size() + n > capacity())
			{
				size_t len = pos - _start;
				reserve(size()+n);
				pos = _start + len;
			}
			//移动数据.因为end_of_storage==finish+n所以不能访问finish+n
			iterator end = _finish+n-1;
			while (end != pos+n-1)
			{
				*end = *(end - n);
				end--;
			}
			//插入数据更新finish
			iterator retPos = pos;
			iterator endPos = pos + n;
			while (pos != endPos)
			{
				*(pos++) = val;
			}
			_finish += n;
			return retPos;
		}
		//任意位置删除
		iterator erase(iterator pos)
		{
			//断言pos位置
			assert(pos >= begin() && pos < end());
			//移动数据,end不能等于pos,这样end+1可能会越界
			iterator end = pos+1;
			while (end != _finish)
			{
				*(end - 1) = *end;
				end++;
			}
			//更新finish
			_finish--;
			return pos;
		}
		iterator erase(iterator first,iterator last)
		{
			assert(first >= begin() && first < end());
			assert(last >= begin() && last >= first && last <= end());
			//记录剩余last至finish数据长度
			size_t overLenght = _finish - last;
			//记录删除数据长度
			size_t eraseLenght = last - first;
			//覆盖被删除的数据空间
			for (int i = 0; i < overLenght; i++)
			{
				*(first++) = *(last++);
			}
			//更新数据长度
			_finish -= eraseLenght;
			return first;

		}
		T& operator[](size_t pos)
		{
			return _start[pos];
		}
		const T& operator[](size_t pos)const
		{
			return _start[pos];
		}
		//获取容量
		size_t size()const 
		{
			return _finish - _start;
		}
		//获取数据长度
		size_t capacity()const
		{
			return _end_of_storage - _start;
		}
	private:
		iterator _start=nullptr;
		iterator _finish=nullptr;
		iterator _end_of_storage=nullptr;
	};
	void test_vector1()
	{
		string s("hello world");
		kk::vector<std::string> vstr1(s);
		kk::vector<std::string> vstr2(vstr1);
		kk::vector<string> vstr3;
		vstr3 = vstr2;
	}
	void test_vector2()
	{
		string s("hello world");
		kk::vector<std::string> vs(s);

		vs.insert(vs.begin(), 2, " yyy ");
		vs.insert(vs.end()," xxx");
		vs.insert(vs.end() - 1, " zzz");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
	}
	void test_vector3()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);

		kk::vector<string>::iterator pos=vs.insert(vs.begin(), 2, " xxx ");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;

		vs.erase(pos);
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;

		vs.insert(vs.begin(), " xxx ");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
		vs.erase(vs.begin()+1,vs.end()-1);
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
	}
	void test_vector4()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);
		cout << "vs.size(): " << vs.size() << " " << " vs.capacity: " << vs.capacity() << endl;
		vs.push_back(" xxx");
		vs.push_back(" yyy");
		vs.push_back(" zzz");
		vs.push_back(" iii");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
		cout <<"vs.size(): " << vs.size() <<" " << " vs.capacity: " << vs.capacity() << endl;
	}
	void test_vector5()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);
		vs.push_back(" xxx");
		vs.push_back(" yyy");
		vs.push_back(" zzz");
		vs.push_back(" iii");
		for (int i = 0; i < vs.size(); i++)
		{
			cout << vs[i];
		}
		cout << endl;
	}
}

3.容易出错的地方

在这里插入图片描述


<think>好的,我现在要帮用户把一段C++代码修改成提取点云中的所有点。用户之前已经询问过如何将硬编码的点替换为从点云读取,现在他们又有一个类似的代码片段,其中只提取了特定的几个点(比如索引0、1、11、87),现在需要改成提取所有点。 首先,我需要理解用户提供的代码。原来的代码是手动创建了一个包含四个点的vector,每个点的坐标来自点云中的特定索引。用户希望改为提取所有点,而不是硬编码的四个。 接下来,我要考虑用户可能的场景。他们可能在处理点云数据,比如从传感器或文件中读取,然后进行后续处理,比如复制或匹配位姿。之前的回答已经涉及了使用PCL库读取点云文件,所以用户可能是在此基础上进一步修改代码。 用户的需求是替换掉硬编码的部分,自动提取所有点。这里需要注意的点是,原来的代码可能是在某个上下文中,比如循环或者特定函数里,访问点云的points成员。用户提供的代码片段中使用了cloud->points[index],所以需要确保cloud是一个有效的点云指针,并且已经被正确加载。 我需要检查用户当前的代码是否存在潜在问题。比如,原来的代码直接访问了索引0、1、11、87,如果点云中的点数不足,这会导致越界错误。现在改为提取所有点后,需要确保点云非空,并且处理可能的异常情况。 然后,我需要思考如何将硬编码的四个点替换为所有点。这可以通过循环遍历点云中的每个点,并将它们的坐标转换为Eigen::Vector3d,然后添加到vector中。这一步在之前的回答中已经提到过,用户可能需要类似的解决方案,但需要针对当前代码进行调整。 可能用户当前的代码中,cloud是一个pcl::PointCloud<pcl::PointXYZ>::Ptr类型的指针,所以需要确保在提取所有点之前,点云已经被正确加载。此外,单位转换的问题也需要考虑,比如点云数据是否是米或毫米,是否需要缩放。 另外,用户提到的“提取所有点”可能意味着不需要任何过滤,直接全部取出。但有时点云可能包含无效点(如NaN),所以是否需要过滤这些点也是需要考虑的。不过,用户没有提到这一点,可能暂时不需要处理,但可以在注意事项中提及。 接下来,我需要给出修改后的代码示例。原来的代码是手动添加四个点,现在需要循环所有点。例如: std::vector<Eigen::Vector3d> cloud_points; for (const auto& p : cloud->points) { cloud_points.emplace_back(p.x, p.y, p.z); } 同时,需要提醒用户注意点云是否为空,避免在空点云时导致程序崩溃。因此,添加异常检查是必要的,比如: if (cloud->empty()) { throw std::runtime_error("点云数据为空"); } 另外,确保点云的坐标系和单位与系统其他部分一致,这也是之前回答中提到的内容,需要再次强调。 用户可能还希望了解如何处理实时数据或进行预处理,但当前问题主要集中在提取所有点,所以可能不需要深入展开,但可以简要提及作为扩展建议。 总结步骤: 1. 替换硬编码的点索引为循环遍历所有点。 2. 添加空点云检查。 3. 确保单位一致。 4. 处理可能的异常情况。 5. 提供修改后的代码示例。 需要确保回答结构清晰,分步骤说明,并指出注意事项,帮助用户避免常见错误。</think>以下是将硬编码的特定点提取修改为提取点云中全部点的分步方案: ```cpp // 原始代码(仅提取部分点) std::vector<Eigen::Vector3d> cloud_points = { {cloud->points[0].x, cloud->points[0].y, cloud->points[0].z}, {cloud->points[1].x, cloud->points[1].y, cloud->points[1].z}, {cloud->points[11].x, cloud->points[11].y, cloud->points[11].z}, {cloud->points[87].x, cloud->points[87].y, cloud->points[87].z} }; // 修改后代码(提取全部点) std::vector<Eigen::Vector3d> cloud_points; cloud_points.reserve(cloud->size()); // 预分配内存提升效率 for (const auto& point : cloud->points) { // 遍历所有点 cloud_points.emplace_back(point.x, point.y, point.z); } ``` **关键修改说明:** 1. **遍历全部点**: - 使用C++11范围for循环 `for (const auto& point : cloud->points)` - 替代手动索引访问方式,避免硬编码索引值 2. **内存优化**: - 添加 `reserve(cloud->size())` 预分配内存 - 防止vector多次扩容影响性能 3. **安全增强**: ```cpp // 添加空数据检查 if (cloud->empty()) { throw std::runtime_error("输入点云为空,无法提取数据"); } // 可选:过滤无效点(NaN) for (const auto& point : cloud->points) { if (!std::isfinite(point.x) || !std::isfinite(point.y) || !std::isfinite(point.z)) { continue; // 跳过无效点 } cloud_points.emplace_back(point.x, point.y, point.z); } ``` **注意事项**: 1. **点云有效性**: - 检查 `cloud` 指针是否已正确初始化 - 确认点云已完成加载(如已执行 `pcl::io::loadPCDFile`) 2. **数据一致性**: - 验证点云坐标系与系统需求是否匹配 - 确认单位制(毫米/米)是否需要转换 3. **性能优化**: - 对大型点云建议添加处理进度提示 - 百万级点云处理示例: ```cpp const size_t total_points = cloud->size(); cloud_points.reserve(total_points); for (size_t i = 0; i < total_points; ++i) { if (i % 100000 == 0) { // 每10万点输出进度 std::cout << "Processing " << i << "/" << total_points << " (" << (i*100/total_points) << "%)" << std::endl; } const auto& p = cloud->points[i]; cloud_points.emplace_back(p.x, p.y, p.z); } ``` **扩展应用**: 1. **带颜色信息的提取**: ```cpp // 针对PointXYZRGB类型点云 std::vector<std::tuple<Eigen::Vector3d, Eigen::Vector3i>> colored_points; for (const auto& p : cloud->points) { Eigen::Vector3d position(p.x, p.y, p.z); Eigen::Vector3i color(p.r, p.g, p.b); colored_points.emplace_back(position, color); } ``` 2. **并行化加速**: ```cpp #include <execution> std::vector<Eigen::Vector3d> cloud_points(cloud->size()); std::transform(std::execution::par, // 并行执行 cloud->points.begin(), cloud->points.end(), cloud_points.begin(), [](const auto& p) { return Eigen::Vector3d(p.x, p.y, p.z); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值