【问题标题】:Finding multiples of five in a vector using a function使用函数在向量中查找五的倍数
【发布时间】:2020-08-22 03:20:03
【问题描述】:

编写一个名为 findMultipleOfFives 的函数,该函数将整数向量作为参数(作为常量引用传递)。如果向量中的每个数字都是数字 5 的倍数,则您的函数应返回 true。否则,该函数应返回 false。

例如,对于给定的向量变量 vector all_values{10, 20, 30, 40, 50},函数 findMultipleOfFives 将返回 true。但是,对于给定的向量变量,vector all_values{10, 24, 30, 40, 5},该函数将返回 false。

我写的代码:

//Name
//This program will determine if a vector has multiples of fives


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


string findMultipleOfFives(vector<int> &all_values);

vector<int> all_values{ 10, 20, 30, 40, 50 };

int main()
{
    cout << "This program will determine whether a vector is full of multiples of five." << endl;
    findMultipleOfFives(all_values);
}

string findMultipleOfFives(vector<int>& all_values)
{
    for (int count = 0; count < 5; count++)
    {
        all_values[count] = 5;
        if (all_values[count] % 5 == 0)
        {
            all_values[count]++;
            return "True";
        }
        else
        {
            return "False";
        }
    }
}

在我的main() 函数中调用该函数时出现错误:

避免使用自定义构造和销毁的未命名对象

除了弄清楚该错误的含义以及我做错了什么之外,我还停留在如何阅读向量的每个元素上。我知道使用模数来确定单个值是否是 5 的倍数,但我不知道如何循环并确定每个值的值并返回真或假。

【问题讨论】:

  • 您是否希望每个人都计算代码中的行数以找到第 17 行,或者您可能想明确指出错误所在的行?将向量中的每个值都赋值为 5 的目的是什么,只是为了查看它在除以 5 时是否有余数。答案当然总是为零。最后,通过阅读作业,您的函数的意图似乎很明显是返回 booltruefalse 而不是文字文本字符串。究竟是什么让你相信这个函数应该返回std::strings,而不是bools?
  • 然后您编辑了您的问题并删除了为向量中的每个值分配 5 的行。发生了什么?您是否复制/粘贴错误,什么样的复制/粘贴错误会插入​​这样的额外行?或者,也许这仍然不是真正的代码?
  • @SamVarshavchik 我编辑并更改了整个部分,因为我一直在尝试修复它?我不习惯使用stackoverflow,我通常使用的网站在您上传时会插入行号。我只是寻求帮助,没有必要居高临下。
  • @yellogs 仅仅因为您正在修复代码并不意味着您应该重新编写问题以匹配您的修复。这会使已发布的 cmets 和答案无效。如果你想显示编辑,那很好,但它们应该在之前的内容之外完成,而不是替换它。
  • @RemyLebeau Gotcha

标签: c++ function for-loop vector


【解决方案1】:

首先,您尝试在循环访问vector 时对其进行修改。您不需要这样做,说明也没有要求您这样做。

其次,指令要求您返回布尔值,而不是字符串。

第三,您的函数没有循环遍历整个向量。 std::vector 有一个 size() 成员来获取元素的实际数量,还有一个 operator[] 来访问元素。但即使使用该大小值,您的循环在第一次迭代时也是 return'ing,因此您只比较第一个元素并忽略其他元素。说明清楚地说明如果 所有 元素都符合条件,则返回 true

试试这个:

//Name
//This program will determine if a vector has multiples of fives


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

bool findMultipleOfFives(const vector<int> &all_values);

int main()
{
    cout << "This program will determine whether a vector is full of multiples of five." << endl;
    vector<int> all_values{ 10, 20, 30, 40, 50 };
    cout << boolalpha << findMultipleOfFives(all_values);
}

bool findMultipleOfFives(const vector<int>& all_values)
{
    if (all_values.empty())
        return false;

    for (size_t count = 0; count < all_values.size(); count++)
    {
        if ((all_values[count] % 5) != 0)
            return false;
    }

    return true;
}

或者,std::vector 可以使用 iterators,例如:

bool findMultipleOfFives(const vector<int>& all_values)
{
    if (all_values.empty())
        return false;

    for (vector<int>::const_iterator iter = all_values.begin(); iter != all_values.end(); ++iter)
    {
        if ((*iter % 5) != 0)
            return false;
    }

    return true;
}

或者,在 C++11 及更高版本中使用基于范围的 for 循环(内部使用 iterators):

bool findMultipleOfFives(const vector<int>& all_values)
{
    if (all_values.empty())
        return false;

    for (int num : all_values)
    {
        if ((num % 5) != 0)
            return false;
    }

    return true;
}

【讨论】:

    【解决方案2】:

    你错了。

    在您的代码中:

    string findMultipleOfFives(vector<int>& all_values)  // the exercise call for a function 
                                                         // that returns bool value, 
                                                         // not a string
    {
       for (int count = 0; count < 5; count++)  // you are looking for multiples of 5, 
                                                // not loop though the first 5 elements.
       {
           all_values[count] = 5;              // Why are you changing the original array?
           if (all_values[count] % 5 == 0)
           {
               all_values[count]++;            // Why are you still changing the original array?
               return "True";                  // You are returning before the end of the loop.
                                               // all elements must be mults of 5  
                                               // to return true.
           }
           else
           {
               return "False";
           }
        }
    }
    

    这是一种写法。

    bool AllAreMuliplesOfFive(const vector<int>& v) // Note the use of const, we do not need to change 
                                                      // or destroy the caller's data.
    {
       for (size_t i = 0; i < v.size(); ++i)  // looping through all elements in v
                                              // v.size() returns a size_t 
       {
           // test condition
           if (v[i] % 5 != 0)   // multiple of 5? 
              return false;     // no, since we need all to be multiple of 5 for success
                                // return false now.
       }
       return true;  // all elements have passed the test!
    }
    

    【讨论】:

    • "return true; // all elements have passed the test!" - 除非vector 为空,否则。由于这只是课堂作业,可能并非如此,但在实践中学会处理是一件好事。这就是我在示例中添加empty() 检查的原因。
    • 这很有帮助,我很感激。
    • 我同意。我确实写它作为练习。毕竟使用 std::all_of() 不需要函数。
    • @yellogs 没问题。既然你是刚开始,你应该在开始编写代码之前尝试用伪代码编写你的函数。你会发现,先收集自己的想法,把算法写下来,对你有很大的帮助。
    【解决方案3】:

    这应该只是一个算法:

    #include <algorithm>
    
    bool findMultipleOfFives(std::vector<int> const& all_values)
    {
      return std::none_of(all_values.cbegin(), 
                          all_values.cend(), 
                          [](int v) { return v % 5; });
    }
    

    正如@RemyLebeau 指出的那样,将其写成all_of 可能更容易阅读:

    bool findMultipleOfFives(std::vector<int> const& all_values)
    {
      return std::all_of(all_values.cbegin(), 
                         all_values.cend(), 
                         [](int v) { return v % 5 == 0; });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      相关资源
      最近更新 更多