![](/img/trans.png)
[英]Array gives correct output for this mergesort function but vector is giving incorrect output. What is going wrong?
[英]Assigning array to std::vector gives incorrect output
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int p[5] = {1,2,3,4,5};
vector<int> x(p[0], p[4]);
class Polynomial {
};
int main(){
Polynomial Poly;
unsigned int i;
for(i = 0;i<=4; i++)
cout<< x[i]<<endl;
return 0;
}
上面的代码输出:
五
-1073741824
0
-1073741824
-2018993448
而我希望它能输出
1
2
3
4
五
为什么输出不正确,我在做什么错?
当i
大于0时,访问x[i]
越界,因为x
是一个包含一个值为5(= p[4]
)的向量(= p[0]
)的向量。
这是因为vector<int> v(a, b)
创建一个向量,每个向量a
元素值为b
。
要实现您想要的目标( x
与p
相同),您需要:
#include <iterator>
vector<int> x(std::begin(p), std::end(p))
或者,您自己猜测大小:
vector<int> x(p, p + 5);
或者也许有点像C:
vector<int> x(p, p + sizeof(p)/sizeof *p);
vector<int> x(p[0], p[4]);
并没有达到您的期望。 它使用p[0]
元素的值p[4]
构造一个vector
。
此std :: vector :: vector的重载将在此处调用。
explicit vector( size_type count,
const T& value,
const Allocator& alloc = Allocator());
如果尝试cout << x.size();
您会发现vector
的大小为1
,当i > 0
超出范围并导致UB时, cout << x[i]
。
您可能要调用此重载:
template< class InputIt >
vector( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
然后将其更改为vector<int> x(&p[0], &p[4]);
。 请注意,这将具有4
元素的构造函数vector
。 vector<int> x(&p[0], &p[5]);
将构造函数vector
与p
所有5
元素一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.