【问题标题】:Cannot convert vector<int> to int* for bool testPIN无法将向量 <int> 转换为 int* 用于 bool testPIN
【发布时间】:2014-09-15 06:48:35
【问题描述】:

对于一个类分配,我不得不使用向量而不是数组来重写这段代码。我想我会使用现有的数组并将它们分配为向量。但我明白了:

错误:无法将参数 '1' 的 'std::vector' 转换为 'int*' '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)
{................}

【问题讨论】:

    标签: c++ arrays vector


    【解决方案1】:

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

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

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

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

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

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

    然后只传递向量:

    testPIN(pin1, pin2);
    

    【讨论】:

      【解决方案2】:
      testPIN(&pin1[0], &pin2[0], NUM_DIGITS)
      

      因为vector的内存结构与array相同。

      请检查一下。

      How to convert vector to array in C++

      【讨论】:

        猜你喜欢
        • 2014-09-19
        • 1970-01-01
        • 2017-02-24
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-05
        相关资源
        最近更新 更多