gpt4 book ai didi

c++ - 在 C++ 中将 SQL 查询返回到 vector 中的函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:34:47 24 4
gpt4 key购买 nike

我在 T-SQL 中有一个查询,它返回 300 条记录。每条记录有 2 列 (date, int)

在 C++ 中,将所有日期放入一个 vector 而将所有整数放入另一个 vector 的最简单方法是什么?

我想在一个函数中完成它。

最佳答案

在不了解您的 SQL 客户端库的情况下很难提供完整的代码 - 这会影响您填充 vector 的方式s,但基本上你循环遍历从数据库中读取的行 push_back在你的两个vector s 表示每行中检索到的值。

主要问题是您将如何处理返回的参数?你有两个 vector s,因为您已在此处指定问题。您可以通过让调用者创建 vector 来实现此目的s 然后函数填充它们,如下所示:

#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
}

为了获得更好的封装或行数据带来的额外功劳,我倾向于使用 POD 结构的 vector 。这样做的好处是每个日期和值都保持紧密耦合 - 如果您希望对每一行执行操作,您可以将其扩展为一个完整的类。最好将数据隐藏在 getter 后面。

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

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

关于c++ - 在 C++ 中将 SQL 查询返回到 vector<double> 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com