【问题标题】:pass vector to function将向量传递给函数
【发布时间】:2014-12-07 02:17:17
【问题描述】:

我正在尝试使此代码正常工作。由于某种原因,该算法没有被调用或没有以正确的方式实现。如果我运行编译得很好的代码,我会得到相同的未排序输入。我尝试了一些通过向量的方法,但我不确定问题在哪里。

#include <iterator>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <vector>





void shift_down(std::vector<int> v, int i, int s){     
        while ( i*2 + 1 < s ) { 
            int child = 2*i + 1; 
            if ((child + 1 < s) && v[child] < v[child+1]) child++;
        if (v[i] < v[child]) {   
            std::swap(v[i],v[child]); 
            i = child;  
        }        
        else            
            return;    
    }
} 

void heap_sort(std::vector<int> v, int s){          
    for (int i = s/2; i >= 0; i--) { 
        shift_down(v, i, s);    
    }
    while (s-1 > 0) {  
        std::swap(v[s-1], v[0]);
        shift_down(v, 0, s-1);  
        s--;
    }
}  


int main(){
    std::string line;
    std::vector<int> vec;

    std::cout << "Please enter numbers seperated by spaces:" << std::endl;
    std::getline(std::cin, line);
    std::istringstream stream(line);

    std::copy(std::istream_iterator<int>(stream),
    std::istream_iterator<int>(),
    std::back_inserter(vec));

    int size = vec.size();

    heap_sort(vec,size);  

    std::copy(vec.begin(),vec.end(),
          std::ostream_iterator<int>(std::cout, "\t"));
    std::cout<<"\t"<<std::endl;

    return 0;
}

【问题讨论】:

  • 通过引用获取向量,你修改了一个函数本地副本。
  • 感谢您的提示,现在可以使用了。 @Borgleader

标签: c++


【解决方案1】:

简单地通过引用获取向量:

void heap_sort(std::vector<int>& v, int s){  
//                             ^

void shift_down(std::vector<int>& v, int i, int s){  
//                              ^

Live demo

您当前正在将传入的向量复制到 v 参数中。 v 在函数内被修改,但更改不会传播到原始向量,只会传播到函数范围内的向量。

【讨论】:

    猜你喜欢
    • 2015-08-07
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多