checking If a vector contains x integers?

Oct 2, 2013 at 9:26pm
If I have a vector that contains 5 integers 2,6,9,19,20 , how can I write an if statement to say if the vector 'contains' 3,6,7,10,21 then do x (the vector changes its values in each loop) so I want to write an if statement to say if it matches the exact values I wrote do something.

The "simplest" way I guess would be a long statement to say if myvec[0] == 3 && myvec[1] == 6 .... but is there a cleaner way than that?
Oct 2, 2013 at 9:29pm
Oct 2, 2013 at 9:45pm
store that 5 ints in array, now go 'for' loop and then compare each array

hope it helps :[]
Oct 2, 2013 at 10:01pm
Oct 2, 2013 at 10:24pm
Do 3, 6, 7, 10, and 21 need to be in that order?
Oct 3, 2013 at 2:46pm
No, but the vector is sorted so thats how they will end up
Oct 3, 2013 at 4:37pm
Did you check those links kesk and I posted? Do you need help?
Oct 3, 2013 at 4:57pm
> The "simplest" way I guess would be a long statement to say if myvec[0] == 3 && myvec[1] == 6 ....
> but is there a cleaner way than that?

Two vectors (of the same type) can be lexicographically compared for equality with == .
http://en.cppreference.com/w/cpp/container/vector/operator_cmp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> seq { 6, 21, 7, 3, 10 } ;

    if( seq == std::vector<int>{ 3, 6, 7, 10, 21 } ) std::cout << "equal\n" ;
    else std::cout << "not equal\n" ;

    std::sort( std::begin(seq), std::end(seq) ) ;

    if( seq == std::vector<int>{ 3, 6, 7, 10, 21 } ) std::cout << "equal\n" ;
    else std::cout << "not equal\n" ;
}

http://coliru.stacked-crooked.com/a/c6d3f0d7d2dd5f8c
Topic archived. No new replies allowed.