如何在向量中找到大于某些数字的所有元素
How to find all elements in vector that are greater than certain number?
所以可以说我有一些类。
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
所以我只想打印最后两个对象。
您将使用循环并访问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
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 为什么使用数组元素查找最大数字的程序不起作用?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 我应该如何使用remove_if删除两个数字范围内的元素
- 查找其元素总和为矩阵中给定数字的路径
- 将数字的字符串数组转换为整数数组时,元素将变为 0
- 每个元素小于某个特定数字的子数组的总和
- 计算向量中大于数字的元素
- 如何将字符串的元素用作数字
- 如何有效地找到数字流中元素的等级
- 如何在向量中找到大于某些数字的所有元素
- 当矢量有 6 个元素(C++、矢量、循环)时,程序打印异常数字
- 如何将向量中的所有元素替换为元素数字的总和
- 将数组的所有元素初始化为相同的数字
- C 如何从向量到给定数字的向量中找到最小元素数量
- 最小元素是特定给定数字的子阵列数量
- 返回连续数字的逻辑假设数组包含元素 1,9,2,3,4,9,6,7,8,那么它应该返回 2,3,4,6,7,8
- 提取整数的数字元素