开发者

Function to return SQL query into a vector<double> in C++

I have a query in T-SQL which returns 300 records. Each record has 2 columns (date, int)

What is the easiest way in C++ to put all the dates in one vector and all the integers in another one?

I would like to do it in开发者_如何转开发 a function.


It's hard to provide full code without knowing your SQL client library - this affects how you populate the vectors, but basically you loop through the rows read from the DB doing push_back on your two vectors for the values retrieved in each row.

The main question is how are you going to handle the returned parameters? You have two vectors, as you have specified the problem here. You could achieve this by having the caller create the vectors and then the function populate them, like this:

#include <vector>

// function declaration - return false on error, or throw exception if preferred
bool populate(std::vector<double>& dates, std::vector<int>& values);

// calling code
std::vector<double> myDates;
std::vector<int> myValues;

// if you know the row count is 300 ahead of time, do this
unsigned int rowCount;

// rowCount gets set up, to 300 in this example
myDates.reserve(rowCount);
myValues.reserve(rowCount);

// Populate vectors, checking for error (false = error)
if (populate(myDates, myValues)) {
  // work with the returned data
}

For extra credit because of better encapsulation or the row data, I would be inclined to use a vector of POD structures. The advantage of this is that each date and value then remain tightly coupled - you can extend this into a full-blown class if you have operations you wish to do for each row. Hide the data behind getters, preferably.

struct Row {
  public:
    double date;
    int value;
};

bool populate(std::vector<Row>& rows);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜