c++ - Do not allow additon of more elements into a vector
问题描述
I need to reserve x number of elements in a std::vector
, say 10. Then I need to write some y number of values into it, say 5 (most of the time y < x). Is there a way to say how many values have been written to it and how may are still available?
Example: Say I allocate 10 elements
std::vector<int> v(10);
But I only fill 7 of these elements
for (unsigned i = 0; i<7; i++)
v[i] = i;
How can I tell that 7 elements have been filled and I still have 3 available?
I tried running
v.size()
and v.capacity()
but both return 10.
解决方案
你的意思是这样的吗?
std::vector<int> a; // dont allocate anything
// allocate memory for 10 elements,
// but dont actually create them. a.size() is still 0.
a.reserve(10);
for(std::size_t i = 0; i < 7; ++i) {
// copy i to a new element at the back
// of the vector. This will never reallocate
// memory, as long as at most 10 elements
// are pushed:
a.push_back(i);
}
// a.size() is now 7
推荐阅读
- spring-boot - WSL2 中的 InteliJ Idea 错误:导出:ProgramFiles(x86): bad variable name
- raspistill - 如何在容器中使用外部命令?
- excel - 以横向和动态范围保存 PDF
- docker - 浏览器会话无法在 elastest 中创建原因:com.spotify.docker.client.exceptions.DockerException
- bots - 如何在任何地方在 IQ bot 自动化中训练图像文件
- api - 空手道 API:忽略“?” 在网址中
- python - websockets中的内存泄漏
- python - Python 正则表达式正面向后看
- wordpress - 删除在除 SAVOY、wordpress 之外的其他完美主题中工作的购物车项目功能
- mongodb - docker-compose, mongodb, 单节点副本集