#c
Вопрос:
Я пытаюсь решить две проблемы с суммами, используя метод грубой силы в c на leetcode, и я продолжаю получать эту ошибку. Что мне делать? Я пытаюсь отобразить вывод.
Это ошибка, которую я получаю:
Line 15: Char 28: warning: expression result unused [-Wunused-value]
return ans1, ans2;
^~~~
Line 15: Char 28: error: no viable conversion from returned value of type 'int' to function return type 'vector<int>'
return ans1, ans2;
^~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:550:7: note: candidate constructor not viable: no known conversion from 'int' to 'const std::vector<int, std::allocator<int>> amp;' for 1st argument
vector(const vectoramp; __x)
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:569:7: note: candidate constructor not viable: no known conversion from 'int' to 'std::vector<int, std::allocator<int>> amp;amp;' for 1st argument
vector(vectoramp;amp;) noexcept = defau<
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:622:7: note: candidate constructor not viable: no known conversion from 'int' to 'initializer_list<std::vector<int, std::allocator<int>>::value_type>' (aka 'initializer_list<int>') for 1st argument
vector(initializer_list<value_type> __l,
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:494:7: note: explicit constructor is not a candidate
vector(const allocator_typeamp; __a) _GLIBCXX_NOEXCEPT
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c /9/bits/stl_vector.h:507:7: note: explicit constructor is not a candidate
vector(size_type __n, const allocator_typeamp; __a = allocator_type())
^
1 warning and 1 error generated.
Вот мой код:
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>amp; nums, int target) {
int n = nums.size();
int ans1,ans2;
for(int i =0;i<n-1;i )
{
for(int j=i 1;j<n;j )
{
if(nums[i] nums[j]==target)
{
nums[i]=ans1;
nums[j]=ans2;
return ans1, ans2;
}
}
}
Комментарии:
1. Вы не опубликовали всю функцию, о которой спрашиваете…
2. Вы ожидаете
return ans1, ans2
создать вектор? Выражение перед запятой отбрасывается, чтобы вы эффективно выполнялиreturn ans2
3. @AlanBirtles это опечатка, из-за которой я создал новую строку для возврата ans2, теперь я просто пытаюсь отобразить вывод.
4. @AmirKirsh это вся функция, скопированная из кода, который я написал
5. Попробуйте сделать:
return {ans1, ans2};
и позже закройте пробел в создании вектора в C .
Ответ №1:
Вам не нужны ans1 и ans2. Ты можешь просто сделать это —
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>amp; nums, int target) {
int n = nums.size();
for(int i =0;i<n-1;i )
{
for(int j=i 1;j<n;j )
{
if(nums[i] nums[j]==target)
{
// {nums[i], nums[j]} will create a vector implicitly
return {nums[i], nums[j]};
}
}
}
Комментарии:
1. когда я это делаю, я получаю следующую ошибку: Строка 18: Символ 5: ошибка: функция, не являющаяся пустой, не возвращает значение во всех путях управления [- Ошибка,- тип возврата] } ^ я предполагаю, что это означает, что элемент управления должен возвращать значение, так как его тип не является пустым
2. Вы можете вернуть недопустимое значение вне цикла for. Недопустимое значение будет означать, что вы не смогли найти ни одной пары чисел с заданной суммой. Например, вы можете добавить
return {-1, -1}
в конце (снаружи) цикла for. Недопустимое значение будет зависеть от вашего входного набора данных.
Ответ №2:
Здесь вы должны вернуть vector<int>
, поэтому вам нужен массив типа vector<int>
, который сохранит индексы результатов.
class Solution {
public:
vector<int> twoSum(vector<int>amp; nums, int target) {
int sum = 0;
vector<int> ind; // it will return index of type vector<int>
int n = nums.size();
for(int i=0; i<n-1; i )
{
for(int j=i 1; j<n; j )
{
if(nums[i] nums[j]; == target)
{
ind.push_back(i); // 1st index
ind.push_back(j); // 2nd index
break;
}
}
}
return ind; //vector<int> type return
}
};