简体   繁体   English

如何重构C ++代码以支持动态数组大小

[英]How to refactor the C++ code to support the dynamic array size

I need to get rid of fixed array size in C++/ODBC apps. 我需要摆脱C ++ / ODBC应用程序中固定的数组大小。 Instead the hardcoded array size (ROWS =10 below) I want to pass the ROWS as the command-line argument. 相反,我想将ROWS作为命令行参数传递给硬编码的数组大小(下面的ROWS = 10)。 I know how to parse the command line. 我知道如何解析命令行。 But how to adjust the following code? 但是如何调整以下代码?

#define ROWS 10

    SQLINTEGER idata[ROWS]
    SQLCHAR cdata1[ROWS][256]
    SQLFLOAT fdata[ROWS]
    SQL_TIMESTAMP_STRUCT ts[ROWS]

    SQLSetStmtAttr(SQL_ATTR_ROW_ARRAY_SIZE, ROWS)

    SQLBindCol(1, &idata)
    SQLBindCol(2, cdata1)
    SQLBindCol(3, fdata)
    SQLBindCol(4, &ts)
    SQLExecDirect("query producing a result-set")

Update: I cannot modify the signature of SQLBindCol(..) 更新:我无法修改SQLBindCol(..)的签名

Let say I will create std::vector instead of SQLFLOAT fdata[ROWS] but how to pass it into SQLBindCol() which does not expect std::vector? 假设我将创建std :: vector而不是SQLFLOAT fdata [ROWS],但是如何将其传递到不期望std :: vector的SQLBindCol()中呢?

Using std::vector on fdata : fdata上使用std::vector

size_t rowCount = /* ... */;
std::vector<SQLFLOAT> fdata(rowCount);
// ...
SQLSetStmtAttr(SQL_ATTR_ROW_ARRAY_SIZE, rowCount);
// ...
SQLBindCol(3, &fdata[0]);
// ...

For cdata1 , std::vector<SQLCHAR> cdata1(250 * rowCount); 对于cdata1std::vector<SQLCHAR> cdata1(250 * rowCount); might work. 可能有用。

I haven't managed to make it work with a 2d dynamic array. 我还没有设法使其与2D动态数组一起使用。 But here's a solution for a dynamic 2d array using a 1d array 但这是使用1d数组的动态2d数组的解决方案

std::set<std::string> getResults(int columnIndex, HSTMT stmt) {
    std::set<std::string> results;
    RETCODE rc = 0;
    int rows = 250;
    int colsize = 500 + 1; //Need to increment colunm size by 1 because SQLBindCol add the terminator character "\0"

    SQLLEN *indicator1 = new SQLLEN[rows];
    char *buff = new char[rows*colsize];
    SQLSetStmtAttr(stmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER)rows, 0);

    SQLUINTEGER     NumRowsFetched;
    SQLSetStmtAttr(stmt, SQL_ATTR_ROWS_FETCHED_PTR, &NumRowsFetched, 0);

    SQLBindCol(stmt, columnIndex, SQL_C_CHAR, buff, colsize, indicator1);
    while (rc = SQLFetch(stmt) == SQL_SUCCESS) {
        for (int i = 0; (SQLUINTEGER)i < NumRowsFetched; i++) {
            results.insert(&buff[i * colsize]);
        }
    }
    delete[] buff;
    return results;

}

Use pointers. 使用指针。

Accept the ROWS argument from command line as you said. 如您所说,从命令行接受ROWS参数。 Allocate memory of desired size (ROWS argument that you get) using dynamic memory allocation by using malloc/new to all the variables you have declared like idata, cdata1 etc. That's it! 通过使用malloc / new向您声明的所有变量(如idata,cdata1等)使用动态内存分配,将所需大小的内存(您获得的ROWS参数)分配给所需的内存。

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

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