简体   繁体   中英

Casting vector<int> to const vector<const int>

How can I cast vector<int> to const vector<const int> ?

I've tried static_cast<const vector<const int>>(array) and using the value without a cast. Neither compiled.

You cannot cast a std::vector<int> to const std::vector<const int> .

Besides, it does not make sense to use a std::vector<const int> at all. It doesn't give you any more safety than a const std::vector<int> .

Not only that, C++ does not allow construction of std::vector<const T> . See Does C++11 allow vector<const T>? for more info.

You cannot change the type of the elements of the vector, but you can change the type of the vector to const std::vector<int> which will prevent making changes to the vector.

#include <vector>

int main()
{
    std::vector<int> v1;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    const std::vector<int>& v2 = v1;
    v2.push_back(4); // Causes an error
    v2[0] = 4; // Causes an error
    return 0;
}

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