从迭代器c++对创建stl向量
Creating stl vector from pair of iterator c++
我正试图从迭代器对创建一个stl向量,但我不确定该向量可能有多少元素。它只能有一个元素。
#include <iostream>
#include <vector>
int main()
{
using namespace std;
vector<int> vect;
for (int nCount=0; nCount < 6; nCount++)
vect.push_back(nCount);
vector<int> second(vect.begin(), vect.begin() );
vector<int>::iterator it; // declare an read-only iterator
it = second.begin(); // assign it to the start of the vector
while (it != second.end()) // while it hasn't reach the end
{
cout << *it << " "; // print the value of the element it points to
it++; // and iterate to the next element
}
cout << endl;
}
我以为向量"second"会有一个元素被vect.begin()指向。事实不是这样吗?
感谢
vector<int> second(vect.begin(), vect.begin() + 1);
向量构造函数使用开放区间,因此不包括结束,即[first, last)
正如lip在评论中指出的那样,它更通用于next
:
second(vect.begin(), next(vect.begin()));
不,事实并非如此。文档非常清晰:
template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() ); (4)
4) 构造具有范围[首先,最后)。
符号"[第一,最后)"表示复制first
和last
之间但不包括last
的所有元素。由于first
==last
,因此不复制任何元素。
进一步阅读文档,您似乎可以使用另一个构造函数:
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator()); (until C++11)
vector( size_type count,
const T& value,
const Allocator& alloc = Allocator()); (since C++11)
这样:
vector<int> second(1, vect.front());
否。在构造函数vector<int> second(vect.begin(), vect.begin());
中,第二个迭代器应该指向超过的末尾,这样您就得到了完全为空的数组。
示例:vect.end()
正好指向向量vect
的末尾,因此vector<int> second(vect.begin(), vect.end());
会将整个vect
复制到second
中。
相关文章:
- 具有 STL 向量类型成员的类的复制内存
- STL 向量无缘无故损坏,VC++ 2017
- 如何避免自定义 STL 向量类的智能指针 delete[] 异常?
- STL向量上出现奇怪的复制构造函数错误
- OpenMP 和不同的 STL 向量
- C++ STL 向量保留太多容量会消耗大量内存吗?
- 使用 boost Spirit 解析为 STL 向量
- C++ 在列表末尾插入元素的列表的 STL 向量
- C++ 使用数组初始化时的 STL 向量内存管理
- 仅编写 c++ stl 向量的第一个元素的正确方法
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 限制指针访问STL ::向量元素
- 传递包裹在shared_ptr中的 STL 向量
- 如何将结构指针插入stl向量中并显示内容
- 将一个STL向量有效地分配给另一个STL矢量(WSL问题)
- erase() 不适用于结构/对象内的 STL 向量
- STL向量具有反向和pop/push_back成本
- 获取 STL 向量C++的地址
- Unique_ptr的 STL 向量 - 如何重置
- 带有 STL 向量的模板函数会因新的分配器而中断