首页 > 解决方案 > c++ boost::split 错误,无法从“初始化列表”转换为“SeqT”

问题描述

我正在使用 boost 库拆分字符串,但出现错误

'<function-style-cast>': cannot convert from 'initializer list' to 'SeqT' 这是 CmdInst.hpp 的第 29 行(它旁边也会有注释)

主文件

#include <iostream>
#include "CmdInst.hpp"

int main() {
    auto inst = cmd::cmdInst();
    inst.start();
}

CmdInst.hpp

#pragma once

#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <vector>


namespace cmd {
    class cmdInst {
        private:
            std::string loc;
        public:
            
            cmdInst(std::string curloc = "") {
                loc = curloc;
            }
            void start() {
                while (true) {
                    std::string cmd;
                    std::cout << "&" << loc << ">";
                    std::cin >> cmd;
                    boost::split(cmd, cmd, boost::is_any_of(" "));

                    if (std::to_string(cmd[0]) == "cd") {
                        if (std::to_string(cmd[1]) == "..") {
                            std::vector<std::string> tloc;
                             
                            boost::split(tloc,loc,boost::is_any_of("/")); //------error here------
                            std::string tmp("");

                            for (size_t i = 0; i < tloc.size() - 1; i++) {
                                tmp += tloc[i]+"/";
                            }

                            loc = tmp;
                        }
                    }
                    else {
                        loc += "/" + cmd[1];
                    }

                    std::cout << "\n";
                }
            }
        
    };
}

该错误实际上来自从 split 函数调用的 boost 库文件夹,但这是我“实际上”导致错误的行

inline SeqT copy_range( const Range& r )
{
      return SeqT( boost::begin( r ), boost::end( r ) ); //error on this line
}

标签: c++visual-studiovisual-c++boostvisual-studio-2019

解决方案


您的代码在此行中有编译器错误(cmd具有 type std::string,因此无法编译):

boost::split(cmd, cmd, boost::is_any_of(" "));

主要的变化就在这两行,我把分割目标改成了std::vector<std::string>

std::vector<std::string> cmds;
boost::split(cmds, cmd, boost::is_any_of(" "));

你也误用std::to_string了,所以我删除了转换。std::to_string用于数字到字符串的转换,这里不合适。

if (cmds[0] == "cd") {
  if (cmds[1] == "..") {
  // ...
  }
}

我已经修复了代码,它是在线托管的。


推荐阅读