【问题标题】:How can I build and use a vector(map(pair(struct))) in C++?如何在 C++ 中构建和使用 vector(map(pair(struct)))?
【发布时间】:2017-07-22 00:05:44
【问题描述】:

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

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

【问题讨论】:

  • 当您依靠猜测而不是阅读文档时,您会得到这样的结果。包括声明您正在使用的标准类型的所需标头(&lt;vector&gt;&lt;string&gt; 等)。在名称前加上 std::。消除*,除非您确实需要将字符串映射到指针并具有指针向量。除非确实需要,否则不要使用运算符 new(这是 C++,而不是 Java 或 C#)。

标签: c++ dictionary vector struct std-pair


【解决方案1】:

考虑不要通过 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 分配(例如,c++11 之前的晦涩框架)
-typedefs 拯救生命
- 如果您不将它们包装成良好的结构,指针可能会很快失控
-objects 可以使用初始化列表 {} 在对象构造期间为它们提供数据。值得注意的是,C 和 C++ 版本 {} 不可交换(st_Base{.foo=10} 在 C 中是合法的,但在 c++ 中是非法的)

【讨论】:

    【解决方案2】:

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

    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);
    

    【讨论】:

      猜你喜欢
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多