所以我有很多问题,但我将从我认为应该很简单的问题开始。我接到一项任务,将模板文件与查询文件进行比较,计算点积,并返回 10 个最近的邻居。我想我可以很容易地进行计算,但是我在处理文件 i/o 时遇到了困难。我能够将数据读入字符串 vector ,但我不确定如何在保持顶点完整性的同时将其转换为 double vector 。如果我尝试使用字符串流或迭代器,我最终会为每个数字分配它自己的索引号,而不是每一行都获得它自己的索引号。这就是我所拥有的……你能帮帮我吗?
为澄清目的而编辑:
我正在将查询文件与包含图像集合的模板文件进行比较,以获得 10 个最近的邻居。查询文件包含一个“集合”(因为缺少更好的描述)。一个模板文件包含 138 行数据。现在,我想做的就是打印模板文件中的每一行数据以及 .dat 文件中相应的索引号,但格式允许我进行必要的计算。一旦一切都说完了,我将需要计算两个 vector (一个查询和模板中的第 i 行)之间的余弦,因此我实际上需要分解模板的第 i 行以计算它之间的余弦和查询文件。这样更清楚吗?
这是查询文件的链接:https://www.dropbox.com/s/6xytafmojrct3lh/001_AU01_query.dat?dl=0 这是模板文件的链接:https://www.dropbox.com/s/vnqi7h1btxdsf9u/001_template.dat?dl=0
示例输出类似于:“001_AU01_query: 15 20 135 19 36 22 105 95 55 68”,其中数字表示与查询数据最匹配的相应模板文件的行号。
再次感谢您的帮助。
void NearestNeighbor::readQuery(){
vector<string> queryVector;
string line;
ifstream queryData;
queryData.open("001_AU01_query.dat");
if (queryData.fail()) {
cout << "Unable to read query.dat file";
exit(1);
}
//populate the vector with the template info
while(getline(queryData, line, '\n')){
queryVector.push_back(line);
}
//this prints the contents of the queryVector to the console
for ( unsigned int i = 0; i < (queryVector.size()); i++){
cout << "Index[" << i << "] " << queryVector[i] << endl;
}
queryData.close();
}//end readQuery()
如果您认为有帮助,我很乐意发布输入样本和预期输出样本。 提前致谢!
最佳答案
您只需要选择正确的数据结构,其他所有内容都应以此为基础。
单个一维 vector<double>
将不起作用,因为您无法跟踪每行数据中的值。但是,vector<double>
适合将值存储在单行数据中。然后你只需要每行之一。
所以更合适的数据结构应该是vector<vector<double>>
.即 2D vector :
void readQuery(std::istream& queryData){
std::vector<std::vector<double>> queryVector;
std::string line;
while(getline(queryData, line, '\n'))
queryVector.push_back(splitData(line));
for (unsigned i = 0u; i != queryVector.size(); ++i) {
std::cout << "Index[" << i << "] ";
for(double value : queryVector[i])
std::cout << value << " ";
std::cout << "\n";
}
}
这需要一个函数 splitData
分割一个string
进入 vector<double>
.您可以在 SO 上找到大量关于拆分字符串的最佳方式的示例(和辩论),但示例实现可能是:
std::vector<double> splitData(const std::string& line) {
std::istringstream iss(line);
std::istream_iterator<double> begin(iss);
std::istream_iterator<double> end;
return {begin, end};
}
Live demo <知识库> Live demo C++03
关于c++将给定.dat文件中的字符串 vector 转换为 double vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281622/