使用 find() 查找向量中的元素
我有一个存储一些整数的向量。在这个向量中,可以有除10、12、31之外的所有数字,不能一起或成对出现,即10和12、10和31、12和31、10、12和31无效。我想出了以下方法:
int main(){
int a[] = {10,2,31}; //can be of any size
vector<int> v(a, a+3);
short cnt = 0;
if(find(v.begin(), v.end(), 10) != v.end())
++cnt;
if(find(v.begin(), v.end(), 12) != v.end())
++cnt;
if(find(v.begin(), v.end(), 31) != v.end())
++cnt;
if(cnt > 1)
cout<<"Invalid options";
else
cout<<"Valid options";
return EXIT_SUCCESS;
}
有效。有更好的方法吗?特别是,由于向量可以包含任意数量的元素,是否有任何缺点?
I have a vector which stores some integers. In this vector, there can be all numbers except 10, 12, 31 cannot appear together or in pairs i.e., 10 and 12, 10 and 31, 12 and 31, 10 12 and 31 are invalid. I have come up with the following approach:
int main(){
int a[] = {10,2,31}; //can be of any size
vector<int> v(a, a+3);
short cnt = 0;
if(find(v.begin(), v.end(), 10) != v.end())
++cnt;
if(find(v.begin(), v.end(), 12) != v.end())
++cnt;
if(find(v.begin(), v.end(), 31) != v.end())
++cnt;
if(cnt > 1)
cout<<"Invalid options";
else
cout<<"Valid options";
return EXIT_SUCCESS;
}
which works. Is there a better way to do this? Especially, since the vector can contain any number of elements, can there be any downside?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
count
怎么样:(参见http://www.cplusplus.com /reference/algorithm/count/)
或
count_if
(仅遍历列表一次):这需要谓词的少量额外工作,例如:
或者你可以更聪明如果您想在运行时指定可能的值,请使用
operator()
创建一个类。(参见http://www.cplusplus.com/reference/algorithm/count_if/ )
关于无效对和三元组的问题是否是一个转移注意力的问题?
How about
count
:(see http://www.cplusplus.com/reference/algorithm/count/)
or,
count_if
(which only traverses the list once):which requires the minor extra work of a predicate, something like:
or you could be more clever and make a class with
operator()
if you want to specify the possible values at runtime.(see http://www.cplusplus.com/reference/algorithm/count_if/)
Is the issue about invalid pairs and triples a red herring?
如果对它们进行排序,则可以使用 std::binary_search ,当向量中的元素数量很大时(虽然需要非常大才能有明显的差异),它会运行得更快。
If you sort them then you can use
std::binary_search
, which will run faster when the number of elements in the vector is large (would need to be very large though to have any noticeable difference).您可以尝试
set_intersection
,如下例所示:You could try a
set_intersection
, as in the example below:即使语句只有 1 行长,也应该始终在 if 语句两边使用方括号。
如果没有括号,阅读代码可能会变得非常混乱。如果您想向该 if 条件添加另一个语句,则可能会引入一个非常难以调试的错误。
You should always use brackets around if statements even if the statement is only 1 line long.
Reading your code can get very confusing without the brackets. And if you want to add another statement to that if condition, you could introduce a very hard to debug error.