2016-03-13 15 views

Odpowiedz

9

C++ 11 ma pojęcie list inicjalizujących. Aby z niego skorzystać, dodaj konstruktor, który akceptuje pojedynczy argument typu std::initializer_list<T>. Przykład:

#include <vector> 
#include <initializer_list> 
#include <iostream> 
struct S 
{ 
    std::vector<int> v_; 
    S(std::initializer_list<int> l) 
    : v_(l) 
    { 
    std::cout << "constructed with initializer list of length " << l.size(); 
    } 
}; 

int main() 
{ 
    S s = { 1, 2, 3 }; 
    return 0; 
} 
2

initializer_list można (jak w innych pojemnikach STL) iteracji i size może być sprawdzony. Pozwala to zrobić tak, jak wskazano w drugiej odpowiedzi przez yuyoyuppe, aby natychmiast przekazać ją do vector. Ale możesz mieć inne zamiary do zainicjowania i wykonać coś takiego, jak wykonać operację bezpośrednio na elementach listy bez kopiowania.

#include <initializer_list> 
#include <iostream> 
#include <algorithm> 

struct S 
{ 
    int thesum; 
    int items; 
    S(std::initializer_list<int> l) : 
    thesum(std::accumulate(l.begin(), l.end(), 0)), 
    items(l.size()) 
    {} 
}; 

int main() 
{ 
    S s = { 1, 2, 3 }; 
    std::cout << s.items << std::endl; 
    std::cout << s.thesum << std::endl; 
    return 0; 
} 

drukuje ten

3 
6 

Patrz:

Powiązane problemy