gpt4 book ai didi

c++ - 使用 C++ 将字符串拆分为键值对

转载 作者:太空狗 更新时间:2023-10-29 23:43:55 24 4
gpt4 key购买 nike

我有这样一个字符串:

"CA: ABCD\nCB: ABFG\nCC: AFBV\nCD: 4567"

现在 ": " 将键与值分开,而 \n 将对分开。我想将键值对添加到 C++ 中的映射中。

考虑到优化,是否有任何有效的方法来做到这一点?

最佳答案

好吧,我这里有两种方法。第一个是我一直使用的简单明了的方法(性能很少成为问题)。第二种方法可能更有效但我没有做过任何正式的计时

在我的测试中,第二种方法大约快 3 倍。

#include <map>
#include <string>
#include <sstream>
#include <iostream>

std::map<std::string, std::string> mappify1(std::string const& s)
{
std::map<std::string, std::string> m;

std::string key, val;
std::istringstream iss(s);

while(std::getline(std::getline(iss, key, ':') >> std::ws, val))
m[key] = val;

return m;
}

std::map<std::string, std::string> mappify2(std::string const& s)
{
std::map<std::string, std::string> m;

std::string::size_type key_pos = 0;
std::string::size_type key_end;
std::string::size_type val_pos;
std::string::size_type val_end;

while((key_end = s.find(':', key_pos)) != std::string::npos)
{
if((val_pos = s.find_first_not_of(": ", key_end)) == std::string::npos)
break;

val_end = s.find('\n', val_pos);
m.emplace(s.substr(key_pos, key_end - key_pos), s.substr(val_pos, val_end - val_pos));

key_pos = val_end;
if(key_pos != std::string::npos)
++key_pos;
}

return m;
}

int main()
{
std::string s = "CA: ABCD\nCB: ABFG\nCC: AFBV\nCD: 4567";

std::cout << "mappify1: " << '\n';

auto m = mappify1(s);
for(auto const& p: m)
std::cout << '{' << p.first << " => " << p.second << '}' << '\n';

std::cout << "mappify2: " << '\n';

m = mappify2(s);
for(auto const& p: m)
std::cout << '{' << p.first << " => " << p.second << '}' << '\n';
}

输出:

mappify1: 
{CA => ABCD}
{CB => ABFG}
{CC => AFBV}
{CD => 4567}
mappify2:
{CA => ABCD}
{CB => ABFG}
{CC => AFBV}
{CD => 4567}

关于c++ - 使用 C++ 将字符串拆分为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38812780/

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