【问题标题】:How do I call a variable based on the value of i in the for loop如何根据 for 循环中 i 的值调用变量
【发布时间】:2021-04-11 11:37:49
【问题描述】:

假设我有一个名为 L0 、 L1 、 L2 .... L9 的变量

如何实现,以便我可以根据此 for 循环上的整数“i”的值调用和递增这些变量之一?

for(int i = 0; i < 10; i++)

我的想法是使用 if 语句或使用 switch,但如果我要多次调用它会极大地影响时间复杂度。

我试着在下面做一个简单的例子:

for(int i = 0; i < 10; i++){

++(L+i) // (if i = 0 -> ++L0, if i = 1 -> ++L1, etc)

}

【问题讨论】:

  • 你应该阅读 std::vector
  • ... 或 std::array 如果变量的数量是固定的。
  • 在页面底部可以看到示例代码:std::array, std::vector
  • 你能解释一下“如果我多次调用它会极大地影响时间复杂度”?这对我来说没有意义。

标签: c++ for-loop increment


【解决方案1】:

我不确定是否有任何方法可以完成您在此处专门尝试做的事情,但您可以使用 std::map 进行类似的操作

#include <iostream>
#include <map>
#include <string>

int main(int argc, char *argv[]) {
    std::map<std::string, int> Lvars = {
        {"L0", 5},
        {"L1", 2},
        
    };

    for (int i = 0; i < 2; ++i) {
        ++Lvars["L" + std::to_string(i)];
    }
}

另一种类似的方法,使用指针。


int main(int argc, char *argv[]) {
    int *L = new int[10]();
    for (int i = 0; i < 10; ++i) {
        ++*(L + i);
    }

    delete[] L;
}

【讨论】:

  • L[i]*(L + i) 的语法糖。 ++L[i] 通常比 ++*(L + i) 更具可读性。
【解决方案2】:

如果您在编译时知道大小,则可以使用数组:

#include <array>
#include <iostream>

int main() {
    std::array L{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    for (auto &el : L) {
        ++el;
    }

    for (auto &el : L) {
        std::cout << el << ' ';
    }
}

输出:

2 3 4 5 6 7 8 9 10 1 

否则你可以使用向量:

#include <iostream>
#include <vector>

int main() {
    std::vector L{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    L.emplace_back(20);
    L.emplace_back(30);

    for (auto &el : L) {
        ++el;
    }

    for (auto &el : L) {
        std::cout << el << ' ';
    }
}

输出:

2 3 4 5 6 7 8 9 10 1 21 31 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多