SNR_BT
SNR_BT

Reputation: 183

How can I declare and define const global vectors in C++?

#include <iostream>
#include <vector>
#include <memory_resource>

using namespace std;

class Test{
    public:
        Test():a{false}{}
        Test TurnOnA(std::pmr::vector<int> aa){
            if(aa.empty()) return *this;
            a=true;
            return *this;
        }
    private:
        bool a;
};

std::pmr::vector<int> test{std::pmr::new_delete_resource()};
const auto my_t = Test{}.TurnOnA(test.insert(test.end(),{1,2,3}));

int main()
{
    cout<<"Hello World";

    return 0;
}

Hello, I need to create a global variable my_t by passing std::pmr::vector to a function from a class. In the above example my_t gives error. How can I solve this and why is the error?

Error message:

prog.cc:20:45: error: cannot convert 'std::vector<int, std::pmr::polymorphic_allocator<int> >::iterator' to 'std::pmr::vector<int>' {aka 'std::vector<int, std::pmr::polymorphic_allocator<int> >'}
   20 | const auto my_t = Test{}.TurnOnA(test.insert(test.end(),{1,2,3}));
      |                                  ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
      |                                             |
      |                                             std::vector<int, std::pmr::polymorphic_allocator<int> >::iterator
prog.cc:10:44: note:   initializing argument 1 of 'Test Test::TurnOnA(std::pmr::vector<int>)'
   10 |         Test TurnOnA(std::pmr::vector<int> aa){
      |                      ~~~~~~~~~~~~~~~~~~~~~~^~

Upvotes: 0

Views: 325

Answers (2)

Werner Henze
Werner Henze

Reputation: 16761

In

const auto my_t = Test{}.TurnOnA(test.insert(test.end(),{1,2,3}));

the test.insert returns an iterator, but TurnOnA requires the complete vector. In a function you would need to write

test.insert(test.end(),{1,2,3});
const auto my_t = Test{}.TurnOnA(test);

In this global variable you would need to write

const auto my_t = Test{}.TurnOnA((test.insert(test.end(),{1,2,3}),test));

But this is bad design, you might run into global object initialization order fiasco. You should better try to encapsulate that in a dedicated function!

Upvotes: 0

eerorika
eerorika

Reputation: 238401

How can I declare and define const global vectors in C++?

Like you did in your excample, but add const. Note that you won't be able to add elements into a const vector after initialisation.

How can I solve this and why is the error?

This is an error because the function expects a vector, and you instead pass an iterator into that function.

Solution: Instead of passing an iterator into the function that expects a vector, pass the vector itself.

Upvotes: 2

Related Questions