What is the simplest way to convert array to vector?

后端 未结 5 1398
醉话见心
醉话见心 2020-11-27 11:24

What is the simplest way to convert array to vector?

void test(vector _array)
{
  ...
}

int x[3]={1, 2, 3};
test(x); // Syntax error.
         


        
5条回答
  •  遥遥无期
    2020-11-27 11:41

    You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

    void test(const std::vector& in) {
      // Iterate over vector and do whatever
    }
    

    becomes:

    template 
    void test(Iterator begin, const Iterator end) {
        // Iterate over range and do whatever
    }
    
    template 
    void test(const Container& in) {
        test(std::begin(in), std::end(in));
    }
    

    Which lets you do:

    int x[3]={1, 2, 3};
    test(x); // Now correct
    

    (Ideone demo)

提交回复
热议问题