gpt4 book ai didi

c++ - 防止循环内外的代码重复

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:15 24 4
gpt4 key购买 nike

我在重写循环时遇到问题:

else if( "d" == option || "debug" == option )
{
debug(debug::always) << "commandline::set_internal_option::setting debug options: "
<< value << ".\n";
string::size_type index = 0;
do
{
const string::size_type previous_index = index+1;
index=value.find( ',', index );
const string item = value.substr(previous_index, index);
debug::type item_enum;
if( !map_value(lib::debug_map, item, item_enum) )
throw lib::commandline_error( "Unknown debug type: " + item, argument_number );

debug(debug::always) << "commandline::set_internal_option::enabling " << item
<< " debug output.\n";
debug(debug::always) << "\n-->s_level=" << debug::s_level << "\n";
debug::s_level = static_cast<debug::type>(debug::s_level ^ item_enum);
debug(debug::always) << "\n-->s_level=" << debug::s_level << "\n";
} while( index != string::npos );
}

value 类似于 string("commandline,parser") 问题是在第一次运行时,我需要 substr(previous_index, index) ,但在每次后续迭代中,我都需要 substr(previous_index+1, index) 来跳过逗号。是否有一些我忽略的简单方法,或者我是否必须在初始迭代的循环外重复调用 find

最佳答案

由于您的目标是防止代码重复:

std::vector<std::string> v;
boost::split(v, value, [](char c) { c == ','; });

如果你想创建自己的拆分函数,你可以这样做:

template<typename PredicateT>
std::vector<std::string> Split(const std::string & in, PredicateT p)
{
std::vector<std::string> v;
auto b = in.begin();
auto e = b;
do {
e = std::find_if(b, in.end(), p);
v.emplace_back(b,e);
b = e + 1;
} while (e != in.end());

return v;
}

关于c++ - 防止循环内外的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8566257/

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