![](/img/trans.png)
[英]C++ /// How do i append a value to an int variable with for and if loop
[英]How do I call a variable based on the value of i in the for loop
假设我有一个名为 L0, L1, L2 .... L9 的变量
我该如何做到这一点,以便我可以根据这个 for 循环上的 integer "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::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;
}
如果您在编译时知道大小,则可以使用数组:
#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 << ' ';
}
}
Output:
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 << ' ';
}
}
Output:
2 3 4 5 6 7 8 9 10 1 21 31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.