搜索结构向量

时间:2019-12-04 13:52:06

标签: c++ algorithm struct iterator find

我有一个这样的结构:

struct Stock{
    int id;
    string title;
    string colour;
    string size;
    int quantity;
    float cost;
}

向量

vector<Stock> all_data;

现在,我想通过ID在 all_data 向量中搜索特定股票。我该怎么办?

3 个答案:

答案 0 :(得分:4)

for(auto data : all_data){
    if(data.id == id)
        std::cout << "Found";
}

答案 1 :(得分:3)

您可以使用标准算法std::find_if。例如

#include <vector>
#include <iterator>
#include <algorithm>

//…

int id = some_value;

auto it = std::find_if( std::begin( all_data ), std::end( all_data ),
                        [=]( const Staock &stocl )
                        {
                            return stock.id == id;
                        } );

if ( it != std::end( all_data ) )
{
    std::cout << it->id << '\n';
}

如果要比较Stock类型的整个对象,或者如果要声明相应的比较运算符,则可以使用函数对象std::equal_tostd::bind来代替lambda。

这是一个使用lambda的演示程序

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

struct Stock{
    int id;
    std::string title;
    std::string colour;
    std::string size;
    int quantity;
    float cost;
};

int main() 
{
    std::vector<Stock> all_data =
    {
        { 1, "A" }, { 2, "B" }, { 3, "C" }, { 4, "D" }, { 5, "E" }
    };

    int id = 3;

    auto it = std::find_if( std::begin( all_data ), std::end( all_data ),
                            [=]( const Stock &stock )
                            {
                                return stock.id == id;
                            } );

    if ( it != std::end( all_data ))
    {
        std::cout << it->id << ": " << it->title << '\n';
    }

    return 0;
}

其输出为

3: C

答案 2 :(得分:1)

您可以尝试类似

it = std::find_if(all_data.begin(), all_data.end(), std::bind(&all_data::id, _1) == data.id);

来自#include <algorithm>

或者,您可以编写自己的函数对象

struct find_id : std::unary_function<Stock, bool> {
    int id;
    find_id(int id):id(id) { }
    bool operator()(Stock const& m) const {
        return m.id == id;
    }
};

it = std::find_if(alll_data.Stock.begin(), all_data.Stock.end(), 
         find_id(currentStockObject));

根据需要进行修改。