从“ double”类型的返回值到函数返回类型“ vector <double>”的可行转换

时间:2019-12-19 09:10:24

标签: c++

我不知道如何将变量类型int转换为vector。

vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
double smalld, t;
for(int i=0;i<queries.size();i++){
    smalld = sqrt(2*queries[i]);
    if(s2>s1){
        t=(sqrt(2)*l-smalld)/(s2-s1);
        return t;
    }else{
        t=(sqrt(2)*l-smalld)/(s2-s1);
        return t;
    }
}}

3 个答案:

答案 0 :(得分:0)

如果要返回return std::vector<double>(1, t),请从方法中vector

答案 1 :(得分:0)

疯狂的猜测,但是我想你想要的是这个

vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
    double smalld, t; 
    vector<double> vec_t;
    for(int i=0;i<queries.size();i++){
        smalld = sqrt(2*queries[i]);
        if(s2>s1){
            t=(sqrt(2)*l-smalld)/(s2-s1);
            vec_t.push_back(t);
        }else{
            t=(sqrt(2)*l-smalld)/(s2-s1);
            vec_t.push_back(t);
        }
    }
    return vec_t;
}

答案 2 :(得分:0)

从您评论中的链接:

  

对于每个形式为 q i 的查询,Sherlock必须报告瓦片重叠面积等于 q i 。

这使我相信输出向量的大小应与输入向量queries相同,所以:

vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
    double smalld, t;
    // the vector to return:
    vector<double> times;
    // reserve space to make push_backs quicker:
    times.reserve(queries.size());

    // you only need to calculate this once for each set of queries
    int rspeed = std::abs(s1 - s2); // the absolute diff in speed

    for(int area : queries) {
        // your formula:
        smalld = sqrt(2 * area);
        t = (sqrt(2) * l - smalld) / rspeed;
        // store the result
        times.push_back(t);
    }

    // and return the resulting vector:
    return times;
}