如何添加两个值,而分裂从boost库
How to add two values while splitting from boost library
这是我使用boost库拆分字符串的代码。
std::vector<std::string> AllCommands;
std::string s="command1;command2;command3"
boost::split(AllCommands,s,boost::is_any_of(";"));
我想在一个结构体上执行相同的操作,其中字符串txt将保存字符串s中的文本,而int I将保存值1。
struct vCmd
{
std::string txt;
int i;
};
std::vector<struct vCmd> AllCommands;
std::string s ("command1;command2;command3")
boost::split(AllCommands,s,boost::is_any_of(";")); // Need to modify this line
为什么不定义自己的容器结构来保存命令并直接使用boost::split
呢?
查看Live on Coliru
- 在
AllCommands
内申报std::iterator
typedef std::iterator<std::forward_iterator_tag, std::string, ptrdiff_t, std::string*, std::string&> iterator;
- 构造函数接受2个迭代器
template<typename Iter> AllCommands(Iter i1, Iter i2)
- 和swap函数
void swap(AllCommands&) {}
计划:
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <string>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <vector>
typedef struct vCmd
{
std::string txt;
int i;
friend std::ostream& operator<<(std::ostream&, const vCmd&);
}vCmd;
std::ostream& operator<<(std::ostream& stream, const vCmd& cmd)
{
stream << " {txt=" << cmd.txt << ",i=" << cmd.i << "} ";
return stream;
}
struct AllCommands
{
typedef std::iterator<std::forward_iterator_tag,
std::string, ptrdiff_t, std::string*, std::string&>
iterator;
AllCommands() {}
template<typename Iter>
AllCommands(Iter i1, Iter i2)
{
std::vector<vCmd> cmds;
//Constrct a vector of vCmd objects
std::for_each(i1, i2, [&cmds](std::string const& t) {
cmds.push_back({t, std::stoi(t.substr(t.find_last_not_of("0123456789") + 1))});
});
//Now print the vector
std::copy(cmds.begin(), cmds.end(), std::ostream_iterator<vCmd>(std::cout, " "));
std::cout << "n";
}
void swap(AllCommands&) {}
};
int main()
{
AllCommands cmds;
boost::split(cmds, "command1;command2;command3", boost::is_any_of(";"));
boost::split(cmds, "command8;command7;command9", boost::is_any_of(";"));
}
输出: {txt=command1,i=1} {txt=command2,i=2} {txt=command3,i=3}
{txt=command8,i=8} {txt=command7,i=7} {txt=command9,i=9}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 使用Boost Interprocess创建托管共享内存需要很长时间
- Boost::posix_time::ptime舍入到给定的分钟数
- 如何添加两个值,而分裂从boost库