English 中文(简体)
C++ []绘图,可能通过模板进行
原标题:C++ [] mapping, possibly through templates

I have a little problem in C++ I don t know how to solve. The first part of the problem is to access an element in a struct via [], or better, to map [] to a subelement.

我的主旨是:

struct e {
    std::string content;
    std::string name;
    std::map<std::string, std::vector<e> > elements;
};

如果我想获得电子内容的话,我可以这样做:e.elements['e1”][0]elements[“e1sub”][0]。

也许可以通过模板来做到这一点,但我不知道如何使用这些模板,而我只是开始学习C++。

罗宾事先获得任何帮助。

最佳回答

您需要超载<代码>。 典型的情况是,你希望实施两种版本的经营者,但自<代码>以来: 只超载非<代码>const版本,可能足以供您使用。

类似以下做法:

struct e {
    std::string content;
    std::string name;
    std::map<std::string, std::vector<e> > elements;

    std::vector<e>& operator[](const std::string& key) {return elements[key];}
};
问题回答

您可以“超载”[]操作者,尝试:

struct e {
    std::string content;
    std::string name;
    std::map<std::string, std::vector<e> > elements;
    std::vector<e>& operator [](const std::string& s);
};

...

std::vector<e>& e::operator [](const std::string& s) {
    return elements[s];
}

你不需要模板。 仅需要<代码>operator[]:

std::vector<e>& e::operator[](std::string const& s) { return this->elements[s]; }
// elements.operator[s] inserts s if it doesn t exist yet. That s non-const so the following won t work
// std::vector<e> const& e::operator[](std::string const& s) const { return this->elements[s]; }




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签