C++ 将数组分配给std::vector会产生不正确的输出

C++ 将数组分配给std::vector会产生不正确的输出,c++,C++,上述代码输出: 五, -1073741824 0 -1073741824 -2018993448 而我希望它能输出 一, 2. 3. 4. 五, 为什么输出不正确,我做错了什么?当I大于0时,访问x[I]超出范围,因为x是一个向量,包含一个值为5=p[4]的=p[0]元素 这是因为创建了一个向量,其中每个元素的值为b 要实现您希望x与p相同的目标,您需要: #include <iostream> #include <vector> #include <string&

上述代码输出:

五, -1073741824 0 -1073741824 -2018993448

而我希望它能输出

一, 2. 3. 4. 五,

为什么输出不正确,我做错了什么?

当I大于0时,访问x[I]超出范围,因为x是一个向量,包含一个值为5=p[4]的=p[0]元素

这是因为创建了一个向量,其中每个元素的值为b

要实现您希望x与p相同的目标,您需要:

#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;


}
或者,自己猜一下尺寸:

#include <iterator>

vector<int> x(std::begin(p), std::end(p))
或者可能有点像C:

vector<int> x(p, p + 5);
向量xp[0],p[4];没有达到你的期望。它用值为p[4]的p[0]元素构造一个向量

将在此处调用此重载

vector<int> x(p, p + sizeof(p)/sizeof *p);

如果您尝试cout@KerrekSB:Hmm,这听起来像是一个可以获得棕色徽章的东西。@OP-FYI,使用at而不是[]来访问循环中的项目,表明输出在抛出异常之前甚至没有到达第二个元素。妈的,我的坏lol,我是新手this@SuzanneElm:没问题。我为你想做的事添加了解决方案。
explicit vector( size_type count,
                 const T& value,
                 const Allocator& alloc = Allocator());
template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );