简体   繁体   English

c ++ find_if结构中的一个元素仅返回第一个元素

[英]c++ find_if an element in struct returning only first element

I want to return the element in struct that has the a=5 . 我想返回具有a=5 struct中的元素。 However, it cannot find it using find_if . 但是,它无法使用find_if找到它。 The value the (*it).a returns is always the first element which is 0. Below is the code. (*it).a返回的值始终是第一个元素,即0。下面是代码。

struct vect_map {
    int a;
    int b;
};
int main () {

    int iteration = 20000;
    vector< vect_map > vect;
    vect.reserve( iteration );
    for( auto i=0; i<iteration; ++i) {
        if( i==iteration-200 ) {
            vect[i].a = 5; 
            vect[i].b = 100;
        }
        else {
            vect[i].a = i; 
            vect[i].b = 1;
        }
    }
    int n=5;
    auto it = find_if( begin( vect ), end( vect ), [&n] (const vect_map &e) { return e.a==n; } );
    if( it!=vect.end() ) {
        cout << (*it).a << endl;
    }
    return 0;

Thank you. 谢谢。

vect[i] has undefined behaviour, because i is not less than vect.size() . vect[i]具有未定义的行为,因为i不少于vect.size()

You need to give your vector the correct size: 您需要给向量提供正确的大小:

vect.resize(iteration);

The problem is that your loop that populates the vector is incorrect: reserve(n) does not create a vector of the desired length, only allows you to push_back without reallocation up to the specified limit. 问题在于,填充vector循环是不正确的: reserve(n)不会创建所需长度的矢量,只允许您push_back而不重新分配指定的限制。

You can fix this problem either by pushing back the desired elements as you go, or by making an array of 2000 items using the appropriate constructor: 您可以通过退回所需的元素来解决此问题,也可以使用适当的构造函数制作2000个项目的数组:

const int iteration = 20000;
vector< vect_map > vect(iteration);

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM