C++11 initializer_list constructor with header and cpp file for custom vector class

女生的网名这么多〃 提交于 2019-12-08 04:46:42

问题


I'm doing a school project where I am to construct a custom vector class. And the class should be able to initialize vectors in a few different ways. I've got stuck with this initializer_list initialization of the vector.

The only values wich are allowed as elements are unsigned int.

header

#include <initializer_list>
class myvec {
private:
    unsigned int *arr; //pointer to array
    std::size_t n; //size of myvec
public:
    myvec(); // Default contructor
    myvec(std::size_t size); // Creating a vec with # of element as size
    myvec(const myvec&); // Copy constructor
    myvec(const initializer_list<unsigned int>& list);

cpp

#include "myvec.h"
#include <initializer_list>

myvec::myvec() {
    arr = new unsigned int[0];
    n = 0;
}

myvec::myvec(std::size_t size) {
    arr = new unsigned int[size];
    n = size;
}

myvec::myvec(const myvec& vec) {
    arr = new unsigned int[vec.n];
    n = vec.n;
    for (int i = 0; i < vec.n; i++) {
        arr[i]=vec.arr[i];
    }
}

myvec::myvec(const std::initializer_list<unsigned int> list) {

}

What I don't understand is how the constructor should be written for it to work? Been trying to find answers on internet for a long time without success.

I want to call the initializer_list constructor from another c++ file as test.cpp

myvec a = {1,2,3,4};

回答1:


Assuming that you are passing the std::initializer_list argument by value (and you can, it is lightweight), you could do something like:

myvec(std::initializer_list<unsigned int> l) : myvec(l.size()) {
  std::copy(std::begin(l), std::end(l), arr);
}

That is, you initialize your internal array with the size() of the list, and you iterate over it with std::begin() and std::end() to copy over its elements.




回答2:


std::initializer_list has 3 member functions:

  • size
  • begin
  • end

And that's all you need.



来源:https://stackoverflow.com/questions/26260331/c11-initializer-list-constructor-with-header-and-cpp-file-for-custom-vector-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!