如何在 C++ 中构建和使用 vector(map(pair(struct)))?

How can I build and use a vector(map(pair(struct))) in C++?

我想构建一个像 vector(map(pair(struct))) 这样的变量并用它来存储 C++ 中的信息,我尝试使用以下代码:

struct st_Base
{
    char Type[2];
    double Price;
    queue<double> Samples;
};

vector< map< string, pair< st_Base, st_Base >* >* > gv_combo;

string str_source = "test123";

gv_combo.push_back(new map<str_source, new pair<st_Base, st_Base>>);

但是当我运行程序时,它总是显示很多错误。谁能告诉我构建它、将数据放入其中并读取它的正确方法?

考虑不通过 new 关键字使用动态分配(手动内存管理容易出错)。如果您的内存需要动态分配,请使用唯一指针 std::unique_ptr

您实质上创建的是一个容器,其中包含一个指向容器的指针,该容器包含一对值(字符串(键)和指向一对结构(值)的指针)。

#include <vector>
#include <map>
#include <utility>
#include <memory>
#include <iostream>



struct st_Base { int foo; };

int main()
{
    typedef std::pair< st_Base, st_Base> weird_pair;
    std::vector<std::map<std::string, weird_pair>> gv_combo;

    string str_source = "test123";
    weird_pair pair = make_pair(st_Base{ 10 }, st_Base{ 11 });
    gv_combo.push_back(std::map<std::string, weird_pair>()); 

    gv_combo.at(0).insert(std::pair<std::string, weird_pair>(str_source, pair));

    std::cout << gv_combo.at(0).at("test123").second.foo;

    return 1;

}

但是这个例子非常难读(至少对我来说)。访问结构成员不是直截了当的(需要调用 at() 来定位地图中的元素,然后使用 first/second 访问适当的 st_Base,这会导致不断增加的调用链。 添加 unique_ptr 会导致 甚至更长的链 ,这会让我的大脑在使用它一段时间后处于报废整个代码的边缘。

OP 注释:
-仔细阅读文档,它是你的朋友
-仅在您确实需要时才使用关键字 new 进行分配(例如,模糊框架 pre c++11)
-typedefs 拯救生命
-如果你不把它们包装成漂亮的结构,指针很快就会失控
-objects 可以使用初始化列表 {} 在对象的构造过程中为它们提供数据。值得注意的是,C 和 C++ 版本 {} 不可互换(st_Base{.foo=10} 在 C 中是合法的,但在 C++ 中是非法的)

这似乎是您要实现的目标:

struct st_Base {
    char Type[2];
    double Price;
    std::queue<double> Samples;
};

std::vector<std::map<std::string, std::pair<st_Base, st_Base>>> gv_combo;

string str_source = "test123";
std::map<std::string, std::pair<st_Base, st_Base>> my_map;
my_map[str_source] = std::make_pair(st_Base(...), st_Base(...)); // instert pair of objects here

gv_combo.push_back(my_map);