如何添加两个值,而分裂从boost库



这是我使用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}  

最新更新