1

我有一个整数向量向量,并且这些向量具有唯一的长度。我想分配一个索引 - 一个整数 i 给整数。例如,如果向量 V 包含 2 个向量,第一个向量 V.at(0) 的长度为 2,第二个向量 V.at(1) 的长度为 4,则索引 3 将对应于第二个向量,V.at(1).at(0)。

我遇到了我怀疑与 const 正确性有关的错误。我该如何解决?

Class A{
...
}

   A func(int i) const {
    int j = 0;
    int sum = 0;
    int u = 0;

    // stop when pass by the j-th vector which i is found
    while (sum < i){
        sum = sum + V.at(j).size();
        ++j;
    }

    // return the position
    u = V.at(j).at(i-sum);
    return A(std::make_pair<j, u>);   
  }

错误信息:

error: the value of 'j' is not usable in a constant expression
     return A(std::make_pair<j, u>);   
                                      ^
note: 'int j' is not const
     int j = 0;
               ^
error: the value of 'u' is not usable in a constant expression
     return A(std::make_pair<j, u>);   
                                         ^
                                         ^
note: 'int uid' is not const
     int u = V.at(j).at(i-sum);
4

1 回答 1

4

应该是括号,而不是尖括号:

return A(std::make_pair(j, u));

尖括号用于模板参数,只能是类型和常量。这就是编译器抱怨变量不是常量的原因。

于 2013-03-04T23:38:48.177 回答