idiocydisaster 2023-03-21 23:21 采纳率: 100%
浏览 44
已结题

关于#c++#的问题,如何解决?c++不允许使用类型名

问题:c++不允许使用类型名。

img


#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    vector<int> sortedSquares(vector<int>& nums)
    {
        int l = 0;
        int r = nums.size() - 1;
        int pos = r;
        vector<int> ans(pos + 1, 0);
        while (l <= r)
        {
            if (abs(nums[r]) > abs(nums[l]))
            {
                ans[pos] = nums[r] * nums[r];
                r--;
                pos--;
            }
            else
            {
                ans[pos] = nums[l] * nums[l];
                l++;
                pos--;
            }
        }
        return ans;
    }
};

int main()
{
    
    vector<int>nums = { -4, -1, 0, 3, 10 };
    vector<int> v;
    v.swap(Solution.sortedSquares(nums));
    for (auto ans : v)
    {
        cout << ans << endl;
    }
}
  • 写回答

3条回答 默认 最新

  • 快乐鹦鹉 2023-03-22 08:50
    关注

    因为你这个类函数不是静态函数,所以不能这么写。一个方法是将函数定义为静态函数,这样可以直接用类域访问静态函数;二是你先定义一个类实例,然后调用这个类实例的函数

     
    #include <iostream>
    #include <vector>
    using namespace std;
     
    class Solution
    {
    public:
        vector<int> sortedSquares(vector<int>& nums)
        {
            int l = 0;
            int r = nums.size() - 1;
            int pos = r;
            vector<int> ans(pos + 1, 0);
            while (l <= r)
            {
                if (abs(nums[r]) > abs(nums[l]))
                {
                    ans[pos] = nums[r] * nums[r];
                    r--;
                    pos--;
                }
                else
                {
                    ans[pos] = nums[l] * nums[l];
                    l++;
                    pos--;
                }
            }
            return ans;
        }
    };
     
    int main()
    {
        
        vector<int>nums = { -4, -1, 0, 3, 10 };
        vector<int> v;
        Solution s;
        v.swap(s.sortedSquares(nums));
        for (auto ans : v)
        {
            cout << ans << endl;
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月30日
  • 已采纳回答 3月22日
  • 创建了问题 3月21日

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要