簡體   English   中英

在函數中填充結構圖的最佳方法是什么

[英]what is the best way of filling map of struct in a function

我有以下代碼:

mystruct
{
    std::string str;
    int x;
}

void main()
{
   std::map<int, mystruct> mymap;
   func(mymap);
}

void func(std::map<int, mystruct>& mmap)
{
   mmap[1].str = "bla";
   mmap[1].x = 5;
}

在功能中填寫地圖的最佳方法是什么? 這樣正確嗎? 結構是在堆棧還是堆上定義的?

有很多原因導致您的代碼不是有效的可編譯C ++代碼。 我已嘗試在下面的示例中修復它們,但除此之外,您看不到任何特別錯誤的方式。

在C ++ 11中,您可以使用初始化列表初始化map 另外,如果要初始化新map則使用返回值代替參考參數會更加慣用:

#include <map>
#include <string>

struct mystruct
{
    std::string str;
    int x;
};

std::map<int, mystruct> func()
{
   return {{1, {"bla", 5}}};
}

int main()
{
   auto myMap = func();
}

map將為元素動態分配內存,因此結構將位於“堆”上。

好吧,這將是一種常見的最小下降方式。 不用擔心取消分配或堆。

#include <map>
#include <iostream>
using namespace std;
struct mystruct
{
   std::string str;
   int x;
   mystruct(int xx, string s) : x(xx), str(s){}
   mystruct() {}
};

void func(std::map<int, mystruct>& mmap, int k, mystruct v)
{
   auto itr = mmap.begin();
   if ((itr = mmap.find(k)) == mmap.end())
   {
      mmap.insert(pair<int, mystruct>(k, v));
   }
   else
   {
      mmap[k] = v;
   }

}

int main()
{
   std::map<int, mystruct> mymap;

   mystruct s(5, "bla");
   func(mymap, 1, s);

   // look up
   if (mymap.find(1) != mymap.end())
   {
      cout << "found";
   }
   else
   {
      cout << "not found";
   }
return 0;
}

如果func旨在將元素添加到可能已經包含元素的現有地圖中,並且不應刪除這些元素,則這是最佳方法:

void func(std::map<int, mystruct>& mmap)
{
   mmap[1] = { "bla", 5 };
}

否則,如果僅將func填充(初始化)一個空映射,則這是最佳方法(前提是您至少使用C ++ 11作為返回值的移動 ):

std::map<int, mystruct> func()
{
   std::map<int, mystruct> mmap;
   mmap[1] = { "bla", 5 };
   return mmap;
   // you could also use list initialization here as shown in Chris Drew's answer
}

auto mymap = func();

在這兩種情況下, mmap都在堆棧上。 將其放在堆上將需要調用std::make_uniquestd::make_sharednew (不要使用它)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM