【问题标题】:Creating a vector in a method and setting it to a variable在方法中创建向量并将其设置为变量
【发布时间】:2013-01-27 20:46:41
【问题描述】:

好的,所以我是 C++ 新手,如果我能问对的话,我相当肯定这应该是一个简单的问题。基本上这是我需要工作的:

printInfoFromVector(this->mycontroller.createVector)

这是我拥有的实际代码:

vector<GasStation>& highPrices = this->myController.findHighestPrice();
    this->findPrice(highPrices);

vector<GasStation>& findHighestPrice(){

我遇到的问题是我无法让它们的 highPrice 类型和 findHighestPrice() 匹配。我很确定问题是因为我正在通过 ref,但我很确定这是正确的方法。

谁能告诉我写赋值语句和方法头以使类型匹配的正确方法?

【问题讨论】:

    标签: c++ vector reference eclipse-cdt


    【解决方案1】:

    如果findHighestPrice 正在计算一个新向量,那么您不应该返回一个引用,而是一个实际的向量。因此,您将拥有:

    vector<GasStation> findHighestPrice() { ... }
    vector<GasStation> highPrices = this->myController.findHighestPrice();
    

    例如,如果您将findHighestPrice 定义为

    vector<GasStation>& findHighestPrice() {
      vector<GasStation> stations;
      // ...
      return stations;
    }
    

    然后stations 将在函数返回时被释放,highPrices 将未定义。

    【讨论】:

    • 谢谢。我试过了,但 id 没有用。但我只是发现这是因为我的项目中其他地方的错误。我想我现在可以工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多