gpt4 book ai didi

c++ - 将一串数据标记为结构 vector ?

转载 作者:搜寻专家 更新时间:2023-10-31 01:57:33 25 4
gpt4 key购买 nike

所以我有以下数据字符串,它是通过 TCP winsock 连接接收的,并且想进行高级标记化,将其转换为结构 vector ,其中每个结构代表一个记录。

std::string buf = "44:william:adama:commander:stuff\n33:luara:roslin:president:data\n"

struct table_t
{
std::string key;
std::string first;
std::string last;
std::string rank;
std::additional;
};

字符串中的每条记录都由回车符分隔。我尝试拆分记录,但尚未拆分字段:

    void tokenize(std::string& str, std::vector< string >records)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of("\n", 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of("\n", lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
records.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of("\n", pos);
// Find next "non-delimiter"
pos = str.find_first_of("\n", lastPos);
}
}

似乎完全没有必要再次重复所有代码以通过冒号(内部字段分隔符)将每条记录进一步标记到结构中并将每个结构插入 vector 中。我确信有更好的方法可以做到这一点,或者设计本身可能是错误的。

感谢您的帮助。

最佳答案

我的解决方案:

struct colon_separated_only: std::ctype<char> 
{
colon_separated_only(): std::ctype<char>(get_table()) {}

static std::ctype_base::mask const* get_table()
{
typedef std::ctype<char> cctype;
static const cctype::mask *const_rc= cctype::classic_table();

static cctype::mask rc[cctype::table_size];
std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));

rc[':'] = std::ctype_base::space;
return &rc[0];
}
};

struct table_t
{
std::string key;
std::string first;
std::string last;
std::string rank;
std::string additional;
};

int main() {
std::string buf = "44:william:adama:commander:stuff\n33:luara:roslin:president:data\n";
stringstream s(buf);
s.imbue(std::locale(std::locale(), new colon_separated_only()));
table_t t;
std::vector<table_t> data;
while ( s >> t.key >> t.first >> t.last >> t.rank >> t.additional )
{
data.push_back(t);
}
for(size_t i = 0 ; i < data.size() ; ++i )
{
cout << data[i].key <<" ";
cout << data[i].first <<" "<<data[i].last <<" ";
cout << data[i].rank <<" "<< data[i].additional << endl;
}
return 0;
}

输出:

44 william adama commander stuff
33 luara roslin president data

在线演示:http://ideone.com/JwZuk


我在这里使用的技术在我对不同问题的另一个解决方案中有描述:

Elegant ways to count the frequency of words in a file

关于c++ - 将一串数据标记为结构 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5462022/

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