user3682078
user3682078

Reputation: 15

How to fix "non-aggregates cannot be initialized with initializer list” <map>

This works in VS2018, but not in 2008, and i'm not sure how to fix it.

#include <map>
#include <string>

int main() {
    std::map<std::string, std::string> myMap = {
        {"Code", "Test"},
        {"Code", "Test1"},
        {"Code", "Test2"},
    };
}

This is the error : Error 2 error C2552: 'myMap' : non-aggregates cannot be initialized with initializer list

Upvotes: 0

Views: 1877

Answers (4)

user7860670
user7860670

Reputation: 37587

Boost.Assign can greatly simplify life:

#include <boost/assign.hpp>

#include <map>
#include <string>

int main()
{
    ::std::map< ::std::string, ::std::string > items;
    ::boost::assign::insert(items)
        ("Code", "Test")
        ("Code", "Test1")
        ("Code", "Test2");
}

Upvotes: 0

eerorika
eerorika

Reputation: 238351

Option 1: Use a compiler that supports C++11 or a later version of the standard where extended list initialisation is well-formed. (I.e. give up on VS2008)

Option 2: Write the program in C++03 (or older if necessary) compliant dialect. An example:

typedef std::map<std::string, std::string> Map;
typedef Map::value_type Pair;

Pair elements[] = {
    Pair("Code", "Test"),
    Pair("Code", "Test1"),
    Pair("Code", "Test2"),
};
const std::size_t length = sizeof(elements)/sizeof(*elements);

Map myMap(elements, elements + length);

Upvotes: 0

Marek R
Marek R

Reputation: 37772

To fix it you have to make it C++03 compliant (this is what vs2008 supports), so basically:

#include <map>
#include <string>

int main() {
    std::map<std::string, std::string> myMap;
    myMap["Code0"] = "Test0";
    myMap["Code1"] = "Test1";
    myMap["Code2"] = "Test2";
}

Upvotes: 0

bolov
bolov

Reputation: 75727

VS2008 is an old compiler that doesn't support C++11 which is needed for this.

You can insert each element:

int main() {
    std::map<std::string, std::string> myMap;

    myMap["Code"] = "Test";
    myMap["Code"] = "Test1";
    myMap["Code"] = "Test2";
}

Or you can use boost:

#include "boost/assign.hpp"

int main() {
    std::map<std::string, std::string> myMap = boost::assign::map_list_of
        ("Code", "Test")
        ("Code", "Test1")
        ("Code", "Test2");
}

Upvotes: 4

Related Questions