本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 将std::vector中的数值拷贝到数组中
原文链接:https://www.stubbornhuang.com/1899/
发布于:2022年01月10日 13:45:30
修改于:2022年01月10日 13:45:30

1 将std::vector中的数值拷贝到数组中
在程序实际运行过程中,为了防止数组越界经常使用stl 容器,但是在做数据交换时经常需要传递数据流的指针,这个时候就需要将stl 容器中的数据拷贝到数组中,当然,只针对int float double这种常规类型的数据。
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
size_t copy(std::vector<T> const& src, T* dest, size_t N)
{
size_t count = std::min(N, src.size());
std::copy(src.begin(), src.begin() + count, dest);
return count;
}
int main()
{
std::vector<int> testVec = {1,2,3,4,5 };
int* indexArray = new int[testVec.size()];
copy(testVec, indexArray, testVec.size());
for (int i = 0; i < 5; ++i)
{
std::cout << indexArray[i] << std::endl;
}
delete[] indexArray;
return 0;
}
运行结果:

当前分类随机文章推荐
- C++ - 一文搞懂std::future、std::promise、std::packaged_task、std::async的使用和相互区别 阅读163次,点赞0次
- C++11 - std::string - stod/stof/stoi/stol/stold/stoll/stoul/stoull,由std::string转换为int/long/float/double等其他类型 阅读3236次,点赞0次
- C++ - 将一维数组/二维数组/三维数组作为函数参数传递给函数 阅读1375次,点赞0次
- C++ - 使用std::chrono获取当前秒级/毫秒级/微秒级/纳秒级时间戳 阅读2964次,点赞0次
- C++ - std::numeric_limits
简介与使用,用于获取指定数据类型的最大值与最小值 阅读213次,点赞0次 - C++ - sleep睡眠函数总结 阅读907次,点赞0次
- C++STL容器 - std::map删除指定元素 阅读1669次,点赞0次
- C++ - 导出接口函数和导出C++类 阅读186次,点赞0次
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读2428次,点赞1次
- C++STL容器 - std::map容器修改、元素操作总结 clear,insert,emplace,erase,swap,merge,extract,insert_or_assign等 阅读1358次,点赞0次
全站随机文章推荐
- 资源分享 - Unity Shader入门精要 PDF下载 阅读2291次,点赞0次
- 资源分享 – OpenGL SuperBible – Comprehensive Tutorial and Reference (Seventh Edition) OpenGL蓝宝书第7版英文高清PDF下载 阅读2329次,点赞2次
- 资源下载 - Go语言实战WilliamKennedy高清带书签PDF下载 阅读2629次,点赞0次
- 资源分享 - Game AI Pro 3 - Collected Wisdom of Game AI Professionals 英文高清PDF下载 阅读2037次,点赞0次
- 计算机图形学 - 如何选择合适的图形API 阅读1303次,点赞0次
- 资源分享 - AI Game Engine Programming , First Edition 英文高清PDF下载 阅读844次,点赞0次
- 计算几何 - C++计算两个二维向量的夹角 阅读3827次,点赞3次
- Modern OpenGL - GLSL着色语言2:GLSL入口函数和GLSL中的变量 阅读2633次,点赞0次
- Python3 - 正则表达式去除字符串中的特殊符号 阅读13089次,点赞1次
- 资源分享 - Digital Image Processing , Third Edition 英文高清PDF下载 阅读1642次,点赞0次
评论
167