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

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

img


#include 
#include 
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;
    }
}

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

 
#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;
    }
}

参考如下:

 
#include <iostream>
#include <vector>
using namespace std;
 
class Solution
{
public:
    static const 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;
    vector<int> temp = Solution::sortedSquares(nums); // 修改
    v.swap(temp);
    for (auto ans : v)
    {
        cout << ans << endl;
    }
}
不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^