I have a static array of struct defined like this :
CViewMgr::ViewInfo g_ViewInfo[] =
{
{ EMainView, ECreateOnce, IDR_MAINFRAME, RUNTIME_CLASS(CMainView),
NULL,0, 0 },
{ EWelcomeView, ECreateAndDestroy, IDR_MENU_OKCANCEL,
RUNTIME_CLASS(CWelcomeView), NULL,0, 0 },
};
I would like to put all these declarations in a vector how can I do it ?
typedef std::vector<ViewInfo> ViewList;
ViewList viewList;
soemthing like :
for (int i = 0; i < _countof(g_ViewInfo); i++)
viewList.push_back(g_ViewInfo[i]);
But I am sure there is an easier way, maybe I should call reserve before ?
Try this:
ViewList viewList(
g_ViewInfo
, g_ViewInfo + sizeof g_ViewInfo / sizeof *g_ViewInfo
);
--
Max
CViewMgr::CViewMgr():
m_viewList(g_ViewInfo, g_ViewInfo + _countof(g_ViewInfo))
{
}
This syntax invokes the constructor of the vector which accepts two
iterators.
There is also vector::insert() which accepts iterators. It is
perfectly fine to append to an empty vector as well:
viewList.insert(
viewList.end()
, g_ViewInfo
, g_ViewInfo + _countof(g_ViewInfo)
);
--
Max
--
Max
It's easier to use the assign() member function rather than insert().
assign() works in the same way as the constructor taking an iterator
range, and thus it's simpler to use.
(Also assign() might be more efficient if there already were some
elements in the data structure. Ok, maybe not with std::vector, but I
know in most implementation of std::list an assign() call will be more
efficient than clear()+insert(), if there were already some elements in
the list.)
Well spotted. I wanted to advise assign() actually, however, I could
not find it on http://www.sgi.com/tech/stl/Vector.html
I should have taken the trouble to open my ISO-IEC-14882_2003_C+
+_Standard.pdf ;)))
> (Also assign() might be more efficient if there already were some
> elements in the data structure. Ok, maybe not with std::vector, but I
> know in most implementation of std::list an assign() call will be more
> efficient than clear()+insert(), if there were already some elements in
> the list.)
I agree.
--
Max