How to initialize a vector with an explicit element initializer?

We can use the following syntax to initialize a vector.

// assume that UserType has a default constructor
vector<UserType> vecCollections; 

Now, if UserType does not provide a default constructor for UserType, but only the constructor as follows:

explicit UserType::UserType(int i) { ... }.

How can I call this explicit element initializer using a vector constructor?

+3
source share
3 answers
vector<UserType> vecCollections(10, UserType(2));
+10
source

Unfortunately, in current C ++ (C ++ 03) there is no way to initialize a vector with arbitrary elements. You can initialize it with the same element as in @Erik's answer.

However, in C ++ 0x you can do this. It is calledinitializer_list

vector<UserType> vecCollections({UserType(1), UserType(5), UserType(10)});

, boost:: assign ,

+4
std::vector<char> items(10, 'A'); //initialize all 10 elements with 'A'

However, if you want to initialize a vector with different values, you can write a template template for a standard vector initializer and use it everywhere:

template<typename T>
struct initializer
{
   std::vector<T> items;
   initializer(const T & item) { items.push_back(item); }
   initializer& operator()(const T & item) 
   {
      items.push_back(item);
      return *this;
   }
   operator std::vector<T>&() { return items ; }
};

int main() {
        std::vector<int> items(initializer<int>(1)(2)(3)(4)(5));
        for (size_t i = 0 ; i < items.size() ; i++ )
           std::cout << items[i] << std::endl;
        return 0;
}

Conclusion:

1
2
3
4
5

Ideon Demo: http://ideone.com/9dODD

+4
source

All Articles