Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

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

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};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...