繁体   English   中英

将数组分配给std :: vector会给出错误的输出

[英]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

要实现您想要的目标( xp相同),您需要:

#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]); 将构造函数vectorp所有5元素一起使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM