0

I have a vector of struct label_diff.

label_diff contains "string" and integer.

I want to check if a vector of label_diff contains equal elements based on the "string"of each element

in .h

struct label_diff {
    string label;
    int diff;

    label_diff(string l = " ", int i = 0)
    {
        label = l;
        diff = i;
    }
};

in main:

int main()
{
    vector<label_diff> KNN;
    label_diff temp;
    temp.label= "Red";
    temp.diff= 25689;

    label_diff temp2;
    temp2.label= "Red";
    temp2.diff= 444;

    label_diff temp3;
    temp3.label= "Red";
    temp3.diff= 0;

    // check if all elements have same label
    if() {cout>>"Same Label"}
    return 0;
}

I know I can loop on the elements with a for loop to know the label name but is there a way to use the built in function std::equal() ?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Maram
  • 37
  • 1
  • 1
  • 6
  • 3
    You could write a proper comparator for your `struct` and then things like that would work automatically. – tadman Apr 15 '16 at 18:34
  • can u show some code? @tadman – Maram Apr 15 '16 at 18:35
  • 1
    Since you're too lazy to search for it, try [these examples](http://fusharblog.com/3-ways-to-define-comparison-functions-in-cpp/). – tadman Apr 15 '16 at 18:36
  • 2
    Any [decent C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1) will teach you how to do that. It's actually pretty trivial. – Rob K Apr 15 '16 at 18:46
  • @Maram Sorry to be so harsh, but I'm not here to do your homework for you. I gave you a suggestion to steer you in the right direction. – tadman Apr 15 '16 at 19:17

1 Answers1

1

If you are using C++11, you can use all_of from <algorithm> combined with a lambda to do this:

if( std::all_of(
        KNN.begin(),
        KNN.end(),
        [&](label_diff l){return l.label == KNN.begin()->label;} ) )
{
    cout << "Same Label"
}

FYI, you << into cout, not >> out of it. You also were not actually putting the labels in the vector. Here is a corrected version that works (you may wish to change this for actual use, such as removing using namespace std;):

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

struct label_diff
{
    string label;
    int diff;

    label_diff(string l = " ", int i = 0)
    {
        label = l;
        diff = i;
    }
};

int main()
{
    vector<label_diff> KNN(3);
    KNN[0].label= "Red";
    KNN[0].diff= 25689;

    KNN[1].label= "Red";
    KNN[1].diff= 444;

    KNN[2].label= "Red";
    KNN[2].diff= 0;

    // check if all elements have same label
    if( std::all_of(
            KNN.begin(),
            KNN.end(),
            [&](label_diff l){return l.label == KNN.begin()->label;} ) )
    {
        cout << "Same Label";
    }

    return 0;
}