2017-04-25 46 views
-6

所以我們說我有一些Class。如何查找矢量中大於某個數字的所有元素?

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 

所以我只想打印最後兩個對象。

+2

在向量的每一個元素都會有一個'amount'是大於,小於或等於20. – NathanOliver

+3

作爲輸出結果,你期望什麼?只包含數量大於20的元素的新矢量,作爲指數集合...? – Corristo

+0

@NathanOliver,看起來像OP想找到大於'20(例如)'的元素。很難找到那些,我想。 – SergeyA

回答

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 
+0

根據@NathanOliver更正,將「i」的類型更改爲「size_t」。 –

+0

爲什麼我需要另一個矢量結果?我可以只使用vector1嗎? – Freak0345

+0

成員'amount'是不可訪問的,因爲'class'成員的默認可見性是私有的。如果您在成員面前指定「public:」,則可以訪問它們;或者將'class'改爲'struct'。 –

相關問題