[英]Error sending std::vector<size_t> array to function and printing
Consider the following program. 考虑以下程序。
#include <iostream>
#include <vector>
void printEm(std::vector<size_t>* array){
std::cout << array[0] << "\n";
}
int main(){
std::vector<size_t> array;
return 0;
}
For some reason, whenever I compile this I get three pages worth or errors and I have no idea why. 出于某种原因,每当我对此进行编译时,我都会得到三页价值或错误,而且我也不知道为什么。 I think the type std::vector might be mismatching with what cout is expectng or something.
我认为std :: vector类型可能与cout所期望的不匹配。 Does anyone know how to fix this?
有谁知道如何解决这一问题? I would post the error messages but they really go on forever.
我会发布错误消息,但它们确实永远存在。 Thanks!
谢谢!
Your array
parameter is a pointer, therefore you need to dereference it. 您的
array
参数是一个指针,因此您需要取消引用它。
void printEm(std::vector<size_t>* array)
{
std::cout << (*array)[0] << "\n";
}
Or pass it by reference: 或通过引用传递它:
void printEm(std::vector<size_t>& array)
{
std::cout << array[0] << "\n";
}
Your passing array
as a pointer so you need to dereference it before you use the []
operator. 您将传递的
array
作为指针,因此在使用[]
运算符之前,需要先对其取消引用。 Try this: 尝试这个:
(*array)[0];
As your code is right now you're trying to access element 0 of an array of std::vector<size_t>
and print that. 由于您的代码正确,因此您正在尝试访问
std::vector<size_t>
数组的元素0并进行打印。
array
is a pointer to a vector, so array[0]
is the vector itself, and you can't write a vector to a stream. array
是指向向量的指针,因此array[0]
是向量本身,因此您不能将向量写入流。
To get the first element you need (*array)[0]
. 要获得第一个元素,您需要
(*array)[0]
。
Although much better would be to pass by (const) reference, where your existing code would just work: 尽管更好的方法是传递(const)引用,但现有代码可以正常工作:
void printEm(const std::vector<size_t> & array)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.