所以我想说我有一些课程。
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
所以我想只打印最后两个对象。
答案 0 :(得分: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