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

问题描述 投票:0回答:2

我想构建一个像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>>);

但是当我运行程序时,它总是向我显示很多错误。任何人都可以告诉我构建它的正确方法,将数据放入其中并阅读它吗?

c++ dictionary vector struct std-pair
2个回答
1
投票

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

你实际上创建的是一个容器,它包含一个指向容器的指针,该容器包含一对值(字符串(键)和指向结构对(value)的指针)。

#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()来定位map中的元素,然后使用first / second访问适当的st_Base,这会导致不断增加的调用链。添加unique_ptr会导致更长的链被放置我的大脑在使用任何一段时间之后都会废弃整个代码。

OP注释: 仔细阅读文档,这是你的朋友 - 只有当你真的需要时才用关键字new来分配(例如,模糊框架前c ++ 11) -typedefs保存生命 如果不将它们包裹在漂亮的结构中,指针可能会很快失控 -objects可以使用初始化列表{}在构造对象期间为它们提供数据。值得注意的是C和C ++版本{}不可交换(st_Base{.foo=10}在C中是合法的,但在c ++中是非法的)


1
投票

这似乎是你想要实现的目标:

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);
© www.soinside.com 2019 - 2024. All rights reserved.