View Full Version : How to check if an int on predefined list of values?
arcull
14th August 2015, 08:51
Hi everybody. I wonder if in C++ or Qt there is some simple way to check if an int equals to some int from a predefined list. I mean something like pseudo code below. Much thanks.
int a = 3;
int b = 8;
int c = 20;
int x = 5;
if (x in [a,b,c]) {
//further processing
}
if (x in [2,7,5]) {
//further processing
}
anda_skoa
14th August 2015, 09:14
Yes.
For example, if the list is a QVector, it has a contains() method.
Or in a QSet if the values are not needed in an ordered fashion.
Similar for STL containers.
Cheers,
_
arcull
15th August 2015, 11:32
Thanks, I guess I got it, but it still feels awkward, is there some shorter way, please post a short snippet, thanks.
QVector<int> vec1(QVector<int>(5));
vec1[0] = 1;
vec1[1] = 2;
qDebug() << "vec1 contains:" << vec1.contains(2);
anda_skoa
15th August 2015, 15:50
It depends.
You can do things like this
QVector<int> vec = QVector<int>() << 1 << 2;
QSet<int> set = QSet<int>() << 1 << 2;
or
typedef QVector<int> IntVector;
typdef QSet<int> IntSet;
IntSet vec = IntVector() << 1 << 2;
IntSet set = IntSet() << 1 << 2;
with C++11 even
auto vec = IntVector() << 1 << 2;
auto set = IntSet() << 1 << 2;
maybe even
auto vec = IntVector{ 1, 2 };
auto set = IntSet{ 1, 2 };
Cheers,
_
arcull
16th August 2015, 08:42
Very good, much thanks ;)
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.