gpt4 book ai didi

c++ - 基于 std::vector 的内容动态设置顺序的模式

转载 作者:太空狗 更新时间:2023-10-29 23:11:07 26 4
gpt4 key购买 nike

我目前正在努力想出一种动态排序的优化方法。我目前在我的代码的某个地方有一个看起来像这样的 vector

std::vector<std::string> vec {
"optionB",
"optionA",
"optionC"
};

上述 vector 中的项目可以打乱顺序。此 vector 中的项目按特定顺序插入,因此上述顺序可以不同。为简单起见,我在声明期间添加了项目。实际情况中大约有 9 个项目,为简单起见,我仅使用 3 个字符串项目。

现在我的代码中的其他地方有类似的东西。

void filter() 
{
bool _optionA,_optionB,_optionC
...
//These boolean variables get assigned values
...
...

/*
Todo : I would like to change the ordering of the
following code based on the ordering of items in the
vector. Currently its in the order _optionA _optionB,
_optionC. I would like this ordering to be based
on the order of the strings as in the above vector.
so it should be _optionB,_optionA,_optionC ,
I understand the items in the vector are string
and the following are boolean types
*/

if(_optionA){
}
if(_optionB) {
}
if(_optionC){
}
}

我想到的最简单的方法是

    for(auto str : vec) 
{
if( (str=="optionA" && _optionA))
{
//This was optionA
}
else if( (str=="optionB" && _optionB)) {

}
else if( (str=="optionC" && _optionC)) {

}
}

我想知道完成上述任务的最优化方法是什么?我正在寻找一种解决方案,可以避免迭代 vector ,因为它位于以性能为中心的代码段中。有没有办法让我使用集成按位运算或数组索引之类的东西来完成这项任务?如果有什么不清楚的地方请告诉我

最佳答案

听起来您想要将字符串映射到实际进程。您能否创建一个接口(interface)选项类并将选项实例映射到应该导致它们出现的字符串?这样你就可以使用字符串作为键来取回一个选项对象并调用类似 myOption.execute() 的东西。

此方法的缺点是每次需要新选项时都需要创建一个新的选项类并让它从接口(interface)继承。

@Edit:抱歉,我想我可能误解了这个问题。但我认为前提仍然适用,您可以拥有一个字符串到 bool 值的映射,并且只需使用该字符串作为键即可返回该选项是打开还是关闭。

关于c++ - 基于 std::vector<string> 的内容动态设置顺序的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51891076/

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