c++ - 无法将 vector<int> 转换为 int* 用于 bool testPIN

标签 c++ arrays vector

对于类作业,我不得不使用 vector 而不是数组重写这段代码。我想我会使用现有的数组并将它们分配为 vector 。但我得到:

error: cannot convert 'std::vector' to 'int*' for argument '1' to 'bool testPIN(int*, int*, int)'

如何解决这个错误?

#include <iostream>
#include<vector>

using namespace std;

// Function Prototype

bool testPIN(int [], int [], int);

int main ()
{
    const int NUM_DIGITS = 7; // Number of digits in a PIN

    int cpin1[NUM_DIGITS] = {2, 4, 1, 8, 7, 9, 0}; // Base set of values.
    int cpin2[NUM_DIGITS] = {2, 4, 6, 8, 7, 9, 0}; 
    int cpin3[NUM_DIGITS] = {1, 2, 3, 4, 5, 6, 7}; 

    vector<int> pin1(cpin1, cpin1+7) ;
    vector<int> pin2(cpin2, cpin2+7) ;
    vector<int> pin3(cpin3, cpin3+7) ;

    if (testPIN(pin1, pin2, NUM_DIGITS))
        cout << "ERROR: pin1 and pin2 report to be the same.\n";

    else
        cout << "SUCCESS: pin1 and pin2 are different.\n";

    if (testPIN(pin1, pin3, NUM_DIGITS))
        cout << "ERROR: pin1 and pin3 report to be the same.\n";

    else
        cout << "SUCCESS: pin1 and pin3 are different.\n";

    if (testPIN(pin1, pin1, NUM_DIGITS))
        cout << "SUCCESS: pin1 and pin1 report to be the same.\n";

    else
        cout << "ERROR: pin1 and pin1 report to be different.\n";

    return 0;

}



bool testPIN(int custPIN[], int databasePIN[], int size)
{................}

最佳答案

在这些情况下,阅读 a good reference 会有所帮助.您需要获取 vector 的基础数据数组:

testPIN(pin1.data(), pin2.data(), NUM_DIGITS))

如果您的实现不支持 C++11,您可以执行以下操作:

testPIN(&pin1[0], &pin2[0], NUM_DIGITS))

但是如果您被要求重新实现一些代码以使用 vector ,您可能需要重新实现 testPIN 函数:

bool testPIN(const std::vector<int>& custPIN1,
             const std::vector<int>& custPIN2);

然后只传递 vector :

testPIN(pin1, pin2);

关于c++ - 无法将 vector<int> 转换为 int* 用于 bool testPIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842273/

相关文章:

c++ - 获取 FastCGI 中的所有客户端 header (C/C++)

c++ - 指向数组的指针,我错过了什么?

javascript - 仅在 .includes() 使用 .find() 找到内容时才返回值

arrays - 如何在 Swift 中使用未知 key 解码 JSON 响应?

c++ - 将 make_shared 与 emplace_back 和 push_back 一起使用 - 有什么区别吗?

c++ - 使用 FFTW 的 'undefined reference' 问题

c++ - 如何使用 read() 在 C++ 套接字中接收超过 40Kb 的数据

php - 将数组转换为逗号分隔值

c++ - vector::max_size 的实际使用

c++ - 如何修复此错误 `conversion from const_iterator to non-scalar type`?