简体   繁体   中英

Const correctness - how to access the elements of a vector of vectors in C++?

I have a vector of vectors of integers, and the vectors have unique lengths. I want to assign an index - an integer i to the integers. For example, if the vector V contains 2 vectors, and the first vector V.at(0) is length 2, and the second vector V.at(1) is length 4, an index 3 will correspond to the first element of the second vector, V.at(1).at(0).

I got errors which I suspect is related to const correctness. How can I fix it?

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 message:

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);

Should be parentheses, not angle brackets:

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

Angle brackets are for template arguments which can only be types and constants. That's why the compiler complains about the variables not being constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM