【问题标题】:set vs. vector of structs with string member设置与带有字符串成员的结构向量
【发布时间】:2013-07-28 19:25:10
【问题描述】:

对于以下定义:

struct Operand
    {
        Operand(std::string opName,bool isInput,bool isOutput,bool isReg) : m_opName(opName),m_isInput(isInput),m_isOutput(isOutput),m_isReg(isReg) {}
        std::string m_opName;
        bool m_isInput;
        bool m_isOutput;
        bool m_isReg;
    };
typedef std::set<Operand> SensitivityList;
SensitivityList m_sensitivityList;

应该执行以下循环:

for (SensitivityList::iterator it = m_sensitivityList.begin();it != m_sensitivityList.end();++it)
    {
        AddToInterfaceList(it->m_opName,portList,portList,false);
}

AddToInterfaceList的签名是:

static void AddToInterfaceList(std::string& data,std::string& interfaceList32Bit,std::string& interfaceList1Bit);

以上代码编译失败,报错:

'AddToInterfaceList' : cannot convert parameter 1 from 'const std::string' to 'std::string &'

如果我将SensitivityList重新定义为:

typedef std::vector<Operand> SensitivityList;

编译成功。set vs.vector有什么问题? 以及如何解决? 谢谢

【问题讨论】:

  • set 的成员是const。要解决此问题,请使用 const std::string&amp; 作为您的函数参数(无处不在;这就是您想要做的)。

标签: c++ string vector stl set


【解决方案1】:

std::set 上的迭代器只能返回对集合中项目的 const 引用。如果您可以获得对该集合的一个项目的非常量引用,则您可以更改该项目的值,这可能使该集合不再是正确的集合。如果将 AddToInterfaceList 的第一个参数更改为 const std::string& data 它应该编译得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多