如何在std :: vector中找到元素位置? [英] How do I find an element position in std::vector?

查看:5065
本文介绍了如何在std :: vector中找到元素位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在std :: vector中找到一个元素位置,用来引用另一个向量中的元素:

I need to find an element position in an std::vector to use it for referencing an element in another vector:

int find( const vector<type>& where, int searchParameter )
{
    for( int i = 0; i < where.size(); i++ ) {
       if( conditionMet( where[i], searchParameter ) ) {
           return i;
       }
    }
    return -1;
}
// caller:
const int position = find( firstVector, parameter );
if( position != -1 ) {
    doAction( secondVector[position] );
}

vector :: size c $ c>返回 size_t ,它对应于不能直接存储 unsigned > -1 。当使用 size_t 而不是 int 作为索引时,如何指示在向量中未找到元素?

however vector::size() returns size_t which corresponds to an unsigned integral type that can't directly store -1. How do I signal that the element is not found in a vector when using size_t instead of int as an index?

推荐答案

您可以使用 std :: numeric_limits< size_t> :: max()找不到的元素。它是一个有效的值,但是不可能创建这样的max索引的容器。如果 std :: vector 的大小等于 std :: numeric_limits< size_t> :: max()允许的索引将为(std :: numeric_limits< size_t> :: max() - 1),因为元素从0开始计数。

You could use std::numeric_limits<size_t>::max() for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector has size equal to std::numeric_limits<size_t>::max(), then maximum allowed index will be (std::numeric_limits<size_t>::max()-1), since elements counted from 0.

这篇关于如何在std :: vector中找到元素位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆