简体   繁体   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;


}

The above code outputs: 上面的代码输出:

5
-1073741824 -1073741824
0 0
-1073741824 -1073741824
-2018993448 -2018993448

Whereas I expect it to output 而我希望它能输出

1 1
2 2
3 3
4 4
5

Why is the output incorrect, and what am I doing wrong? 为什么输出不正确,我在做什么错?

The access x[i] is out of bounds when i is greater than 0, since x is a vector containing one (= p[0] ) element of value 5 (= p[4] ). i大于0时,访问x[i]越界,因为x是一个包含一个值为5(= p[4] )的向量(= p[0] )的向量。

This is because vector<int> v(a, b) creates a vector with a elements with value b each. 这是因为vector<int> v(a, b)创建一个向量,每个向量a元素值为b

To achieve what you want ( x being the same as p ), you need: 要实现您想要的目标( xp相同),您需要:

#include <iterator>

vector<int> x(std::begin(p), std::end(p))

Or, guessing the size yourself: 或者,您自己猜测大小:

vector<int> x(p, p + 5);

Or perhaps somewhat C-like: 或者也许有点像C:

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

vector<int> x(p[0], p[4]); doesn't do what you expect. 并没有达到您的期望。 It constructs a vector with p[0] elements of value p[4] . 它使用p[0]元素的值p[4]构造一个vector

This overload of std::vector::vector will be called here. std :: vector :: vector的重载将在此处调用。

explicit vector( size_type count,
                 const T& value,
                 const Allocator& alloc = Allocator());

If you try cout << x.size(); 如果尝试cout << x.size(); you'll find the size of vector is 1 , cout << x[i] when i > 0 is out of bound and leads to UB. 您会发现vector的大小为1 ,当i > 0超出范围并导致UB时, cout << x[i]

You might want to call this overload: 您可能要调用此重载:

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

Then change it to vector<int> x(&p[0], &p[4]); 然后将其更改为vector<int> x(&p[0], &p[4]); . Note this will constructor vector with 4 elements. 请注意,这将具有4元素的构造函数vector vector<int> x(&p[0], &p[5]); will constructor vector with all the 5 elements from p . 将构造函数vectorp所有5元素一起使用。

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

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