【发布时间】:2015-06-14 16:06:58
【问题描述】:
我写了以下简单的例子:
#include<iostream>
#include<vector>
int main()
{
int arr[] = {1, 2, 4, 7, 10};
std::vector<int> vect;
vect.assign(arr, arr + 5);
for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
{
std::cout << *it << std::endl;
}
std::cout << "-------------------------------------" << std::endl;
for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
{
std::cout << *it << std::endl;
}
}
两个循环的打印结果都是一样的。我的问题是它可靠吗?遍历向量是否每次都以相同的顺序返回elemtns?我的意思是,它是标准化的还是允许某些实现以不同的顺序迭代向量。例如,我们第一次迭代向量如下:
for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
{
std::cout << *it << std::endl;
}
得到输出
1
2
4
7
10
同时,第二次迭代产生输出:
2
10
1
4
7
这对于某些实现是可能的吗?
【问题讨论】:
-
它可靠吗?:只要 STL 容器的内容不改变,每次迭代它都会得到相同的输出。这是有保证的行为。
-
不,我不这么认为——因为这些向量将在内部被实现为数组或 LinkedList——主要是数组(可调整大小),并且尝试做一些每次都会改变的事情对于实现来说很难.除非你愿意! :) 在那种情况下,你自己写! :)
-
输出真的不一样吗?我在CodeChef IDE 上运行了你的代码,结果是一样的。
-
@gabhijit 它们必须实现为连续存储