使用循环和变量模式(序列)

C++: Using loops and variable patterns (sequence)

本文关键字:序列 模式 变量 循环      更新时间:2023-10-16

我有一个例程函数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风格的循环。