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
148 views
in Technique[技术] by (71.8m points)

c++ - How to make assignments in Constructor using initialisation list

I'm trying to make a constructor for my own Vector class, to which I pass the length of the vector to be made and a single default value to fill it.

How am I supposed to iterate through every item of the array_ in order to asign them to value using an initialisation list as below?

This would have been easy to do, were I to use a constructor body. But I've read that using an initialisation list is better.

class Vector{
private:
int size_;
int* array_;

public:
Vector(int length, int value) : size_(length), array_(new int[length * 2]) { }

}
question from:https://stackoverflow.com/questions/65923740/how-to-make-assignments-in-constructor-using-initialisation-list

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

1 Reply

0 votes
by (71.8m points)

You cant use just initializer lists to get it done. Use std::fill_n like this,

class Vector{
private:
int size_;
int* array_;

public:
Vector(int length, int value) : size_(length), array_(new int[length * 2]) 
{ 
    std::fill_n(array_, length, 0);
}

}

Note: Using array_(new int[length * 2]) might not be the best way to allocate the buffer. For example, if the user wants to store just 100 integers, you actually allocate 200 entries worth of memory. This might be a good idea for performance but might not be for memory. Another thing is that your vector only supports integers. If you want to support other types as well, make it a templated class.


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

...