Initializing unspecified number of integers in a class

How can I define a class that receives unspecified number of integers?
My purpose is code a program that acts similar "vector".
Last edited on
With std::initializer_list.
You can also consider a variadic template constructor, but this is less ideal because of the overload resolution mechanism's preference for that constructor over many other near matches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# include <memory>
# include <initializer_list>
# include <iostream>

class A { 
  std::ptrdiff_t size;
  std::unique_ptr<int[]> data; 
  
  template <typename Iterator>
  A(Iterator&& b, Iterator&& e)
    : size{std::distance(b, e)}
    , data{std::make_unique<int[]>(size)} 
  { std::copy(b, e, data.get()); }

public:
  A(std::initializer_list<int> l)
    : A(l.begin(), l.end()) {}
  
  int* begin() const { return data.get(); }
  int* end()   const { return data.get() + size; }
};

int main() { 
    A a { 1, 2, 3, 4, 5 }; 
    for (auto elt: a) std::cout << elt << '\n';
}
Last edited on
thanks;but
In debugging this program below error appears:

'std::copy::_Unchecked_iterators::_Deprecate': Call to 'std::copy' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' Project2 c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.11.25503\include\xutility

can you resolve it?
I work with visual studio 2017.
this call relies on the caller to check that the passed values are correct

Who would have guessed.

In all seriousness, Microsoft seems to be over-eager.

Live demo:
http://coliru.stacked-crooked.com/a/e9c29239f9dda0bf

I would most likely disable that message, for what it's worth. But if you would prefer not to, you may use this non-standard iterator adaptor as per the instructions here:
https://stackoverflow.com/questions/12062262/stditerator-pointers-and-vc-warning-c4996/12063174#12063174

See also:
https://msdn.microsoft.com/en-us/library/aa985965.aspx

Alternatively, you may change the design. No matter what the compiler says about std::copy, std::initializer_list is still the subject of the answer - the rest of the code is only an example.

Last edited on
Topic archived. No new replies allowed.