简体   繁体   中英

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. 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.

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. 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.

array is a pointer to a vector, so array[0] is the vector itself, and you can't write a vector to a stream.

To get the first element you need (*array)[0] .

Although much better would be to pass by (const) reference, where your existing code would just work:

void printEm(const std::vector<size_t> & array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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