【问题标题】:How to find all elements in vector that are greater than certain number? [duplicate]如何找到向量中大于某个数字的所有元素? [复制]
【发布时间】:2017-04-25 19:00:50
【问题描述】:

假设我有一些课程。

Class Example
{
int amount;
string name;
}
//constructors
...........
.....
int geAmount()
{
return amount;
}

然后我创建对象向量。

Vector <Example> vector1;

如何找到数量大于的所有元素 20(例如)? 我想打印它们..

例如我有 3 个对象。

Name=abc amount 5
Name=bcd amount 25
Name=dcg amount 45

所以我只想打印最后两个对象。

【问题讨论】:

  • 向量中的每个元素都有一个大于、小于或等于 20 的amount
  • 您对输出的期望是什么?一个仅包含数量大于 20 的元素的新向量,作为一组索引,...?
  • @NathanOliver,看起来 OP 想要查找大于 20(for example) 的元素。我想这些很难找到。
  • std::copy_if 是你的朋友。
  • @RSahu 或者std::count_if。如果需要的话,索引会有些困难。

标签: c++


【解决方案1】:

您将使用循环并访问amount 成员:

#include <iostream>
#include <vector>
#include <string>

struct Record
{
  int amount;
  std::string name;
};

static const Record database[] =
{
  {  5, "Padme"},
  {100, "Luke"},
  { 15, "Han"},
  { 50, "Anakin"},
};
const size_t database_size =
    sizeof(database) / sizeof(database[0]);

int main()
{
    std::vector<Record> vector1;

    // Load the vector from the test data.
    for (size_t index = 0; index < database_size; ++index)
    {
        vector1.push_back(database[index]);
    }

    const int key_amount = 20;
    const size_t quantity = vector1.size();
    for (size_t i = 0U; i < quantity; ++i)
    {
      const int amount = vector1[i].amount;
      if (amount > key_amount)
      {
        std::cout << "Found at [" << i << "]: "
                  << amount << ", "
                  << vector1[i].name
                  << "\n";
      }
    }
    return 0;
}

这是输出:

$ ./main.exe
Found at [1]: 100, Luke
Found at [3]: 50, Anakin

【讨论】:

  • 根据@NathanOliver 更正,将i 的类型更改为size_t
  • 为什么我需要另一个向量结果?我可以只使用vector1吗?
  • 成员 amount 不可访问,因为 class 成员的默认可见性是私有的。如果您在成员之前指定public:,则可以访问它们;或将class 更改为struct
  • results 向量包含所有大于key_amount 的值。向量results 不是必需的。
  • 你能解释一下这几行吗: const size_t quantity = st.size(); for (size_t i = 0U; i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多