为什么我的向量是空的?
Why is my vector empty?
我想创建一个简单的倒排索引。我有一个文件,其中包含每个文档中的 docId 和关键字。所以第一步是尝试读取文件并对文本文件进行标记。我在网上找到了一个应该可以工作的标记化功能并对其进行了一些更改。我想在空白 space 之后标记每个单词。我的文本文件没有任何逗号或句号。对文本文件进行标记后,标记存储在向量中。因此,在 运行 tokenize
函数之后,我尝试打印出向量的元素,但没有任何反应。然后我尝试打印出矢量的大小,结果我得到 0
。这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "functions.h"
#include "vector"
using namespace std;
int main()
{
string line;
vector<string> v;
ifstream myfile("test.txt");
if(myfile.is_open()){
while(getline(myfile,line)){
//cout << line << '\n';
tokenize(line, ' ', v);
}
myfile.close();
}
else cout << "Unable to open file";
cout << v.size() << '\n';
return 0;
}
这是我的分词函数:
using namespace std;
void tokenize(string s, char c, vector<string> v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
我不能使用 strtok
,因为我稍后会在程序中使用线程,而且我在论坛上看到 strtok
不能很好地使用线程。
Why is my vector empty?
因为您要按值传递 vector
:
void tokenize(string s, char c, vector<string> v) {
改成参考:
void tokenize(string s, char c, vector<string>& v) {
我想创建一个简单的倒排索引。我有一个文件,其中包含每个文档中的 docId 和关键字。所以第一步是尝试读取文件并对文本文件进行标记。我在网上找到了一个应该可以工作的标记化功能并对其进行了一些更改。我想在空白 space 之后标记每个单词。我的文本文件没有任何逗号或句号。对文本文件进行标记后,标记存储在向量中。因此,在 运行 tokenize
函数之后,我尝试打印出向量的元素,但没有任何反应。然后我尝试打印出矢量的大小,结果我得到 0
。这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "functions.h"
#include "vector"
using namespace std;
int main()
{
string line;
vector<string> v;
ifstream myfile("test.txt");
if(myfile.is_open()){
while(getline(myfile,line)){
//cout << line << '\n';
tokenize(line, ' ', v);
}
myfile.close();
}
else cout << "Unable to open file";
cout << v.size() << '\n';
return 0;
}
这是我的分词函数:
using namespace std;
void tokenize(string s, char c, vector<string> v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
我不能使用 strtok
,因为我稍后会在程序中使用线程,而且我在论坛上看到 strtok
不能很好地使用线程。
Why is my vector empty?
因为您要按值传递 vector
:
void tokenize(string s, char c, vector<string> v) {
改成参考:
void tokenize(string s, char c, vector<string>& v) {