使用循环和变量模式(序列)
C++: Using loops and variable patterns (sequence)
我有一个例程函数process_letter_location(const char& c, string &word)
。
在main中声明了一系列字符串变量,如下所示:
string sf_1 = "something", sf_2 = "something", sf_3 = "something",
sf_4 = "something";
我有一个string word
,我把我的例程函数称为so
process_letter_location(word[0], sf_1);
process_letter_location(word[1], sf_2);
process_letter_location(word[2], sf_3);
process_letter_location(word[3], sf_4);
这看起来有点乱,但我知道我可以使用一个循环来调用例程,如
for(int i=0; i < 4; i++) {
process_letter_location (word[i], ?)
}
但是我不确定我将如何分配第二个参数。变量的共同点是"sf_",唯一改变的是数字。我是否可以将这个例程调用合并到循环中?如果没有,有没有更好的方法来实现这段代码?
任何帮助都会很感激。由于
可以使用数组:
string sf[4] = { "something1", "something2", "something3", "something4"};
然后循环:
for(int i=0; i < 4; i++) {
process_letter_location (word[i], sf[i]);
}
你应该使用数组。你的用例要求它应该是一个数组。
但是如果你只能改变处理变量的方式,你也可以使用可变的模板函数。
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
void process_letter_location(char c, string const& str)
{
cout << str << 'n';
}
void process_strings(char* buf, string const& str)
{
process_letter_location(*buf, str);
}
template<typename... Args>
auto process_strings(char* buf, string const& str, Args... args)
-> typename enable_if<sizeof...(Args)>::type
{
process_letter_location(*buf, str);
process_strings (++buf, args...);
}
int main() {
string sf_1 = "something1",
sf_2 = "something2",
sf_3 = "something3",
sf_4 = "something4";
char buff[10];
process_strings(buff, sf_1, sf_2, sf_3, sf_4);
return 0;
}
这是展开循环的一种奇特方式。看到
您可以从以下重构开始:将string
替换为string * const
在函数process_letter_location
中。(调整函数定义相应的)。
然后你可以用string指针填充你喜欢的容器然后循环。
我认为你可以从这次重构中学到很多c++知识。
让我来演示如何编写循环:
std::vector<std::string*> strings = {&sf_1,
&sf_2,
&sf_3,
&sf_4};
for(int i=0; i < 4; i++) {
process_letter_location (word[i], strings[i]);
}
则可以考虑使用迭代器而不是c风格的循环。
相关文章:
- 大量序列中核苷酸类型的快速计数
- 递归函数计算序列中的平方和(并输出过程)
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 从给定的 I 和 D 序列中形成最小数
- 如何在C++中序列化结构数据
- 具有最大子序列大小的序列,每个元素都相同
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 序列化模式类似于boost::序列化
- 逻辑:如何在C / C++中打印Pseudo_random位序列模式
- 使用自定义模式进行序列化,并使用Boost进行随机访问
- C 双重调度,出厂模式或一种从接收到的序列数据创建派生对象的方法
- 在具有重复项的长数据序列的滚动窗口中查找模式
- 检查序列中的位模式
- 增强mpl序列模式匹配
- 使用循环和变量模式(序列)
- 如何测试一个序列是否符合给定模式中的另一个序列
- 需要在Windows32模式下序列化位图
- C++,序列模式下二进制文件的问题