在函数中通过不同名称引用全局向量

referencing a global vector by a different name within a function

假设您有三个全局向量 V1、V2 和 V3。

假设您有一个函数,它对由 int 值确定的上述向量之一执行一组操作,例如 VN[3]++。

在 python 我会做这样的事情:

global:
    v1 = [1,2,3]
    v2 = [1,2,3]
    v3 = [1,2,3]
    lists = [v1, v2, v3]

def function (determiner):
    list = lists[determiner]
    list[1] += 1...

我认为理论上我可以为确定符的每个可能值设置单独的 ifs,但多次重复一段代码似乎是错误的代码。 (1) 解决这个问题的正确方法是什么?我假设我会使用指针,但我今天才了解它们并且我一直在努力让我的代码工作。这是我一直在尝试的代码示例。

   vector <int> counts0;
   vector <int> counts1;

   void editor(int determiner){
        if (determiner == 1) {
            vector<int> & count_l = counts1;
        }
        else if (determiner = 2) {
            vector<int> & count_l = counts2;
        }
        count_l[5]++;
    }

有两种方法可以实现这一点,具体取决于您的期望。如果 lists 应该引用向量,请使用指针(如您所说,请记住在索引之前取消引用)

std::vector<int> a, b, c;
std::vector<std::vector<int>*> lists = {&a, &b, &c};

void editor(int determiner)
{
    (*lists[determiner])[5]++;
}

如果您想要 list 中所有向量的副本,请不要使用指针(当您大量修改 lists 时,这可能会很昂贵,只能对 const 数据使用这种方法)。

std::vector<std::vector<int>> lists = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}};

void editor(int determiner)
{
    lists[determiner][5]++;
}