如何创建结构数组类型的地图对象

时间:2016-06-30 18:12:58

标签: c++

<Button x:Name="button3" 
        Content="Play Sound 3" 
        HorizontalAlignment="Stretch" 
        Grid.Row="2" 
        VerticalAlignment="Stretch" 
        Margin="0,0,0,0" 
        d:LayoutOverrides="Width, Height" 
        FontSize="20" 
        Foreground="{StaticResource PaleGreyBrush}" 
        Background="{StaticResource DarkGreyBrush}" 
        Style="{StaticResource ActionsButton}" 
        BorderBrush="{StaticResource HighlightBrush}">
            <Interactivity:Interaction.Behaviors>
                <Interactions:EventTriggerBehavior EventName="Click" SourceObject="{Binding ElementName=button3}">
                    <Media:PlaySoundAction Source="Assets/Whistle.mp3" Volume="1"/>
                </Interactions:EventTriggerBehavior>
            </Interactivity:Interaction.Behaviors>
</Button>

我想创建一个my_struct类型的地图对象。

typedef struct
{
int    m_x[5];
int    m_y[5];
} my_struct;

在for循环中,我想将值初始化为struct的成员。我该怎么做,如果我想在一个函数中执行此操作并返回map_object,我将返回什么内容?

2 个答案:

答案 0 :(得分:1)

以下示例显示了如何在for循环中使用结构填充地图。它还显示了如何访问结构成员。

#include <array>
#include <map>
#include <iostream>

struct my_struct
{
    std::array<int, 5> m_x;
    std::array<int, 5> m_y;

    my_struct(std::array<int, 5> x, std::array<int, 5> y) : m_x(x), m_y(y)
    {}
};


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

    // Adding elements to the map using a for loop
    for (int i = 0; i < 3; ++i)
    {
        std::array<int, 5> x = { i,i,i,i,i };
        std::array<int, 5> y = { 0,0,0,i,i };
        myMap.insert(std::pair<int, my_struct>(i, my_struct(x,y)));
    }

    // accessing m_x
    std::cout << "Member with key 1 has m_x[0] value of: " 
              << myMap.at(1).m_x[0] << std::endl;
}

要让一个函数返回一个地图,你只需像现代C ++一样返回地图,编译器应该不需要深层复制。

std::map<int, my_struct> getAMap()
{
    std::map<int, my_struct> myMap;

    // Adding elements to the map using a for loop
    for (int i = 0; i < 3; ++i)
    // ...

    return myMap;
}

int main()
{
    auto myMap = getAMap();

    // accessing m_x
    std::cout << "Member with key 1 has m_x[0] value of: " 
              << myMap.at(1).m_x[0] << std::endl;
}

答案 1 :(得分:0)

试试这个:

std::map<int, my_struct>::iterator it = map_object.begin();
while (it != map_object.end()){
    my_struct& struct_to_intialize = it->second;
    //do things with struct_to_initialize
    it++;
}

但是,如果你为你的结构包含一个构造函数,比如:

my_struct::my_struct(){
    //initialize as you please
}

然后一切都可以隐含地完成。

注意:在C ++中不需要typedef,你应该将结构声明为

struct my_struct {
    int m_x[5];
    int m_y[5];
};