检查数组索引存在 [英] Check if array index exists

查看:103
本文介绍了检查数组索引存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法来检查数组的给定索引的存在?
我想设置的数值指标,但像1,5,6,10。所以,我想看看是否存在,这些指标,如果他们不只是增加另一个柜台。

Is there any way to check if a given index of an array exists? I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.

我通常使用PHP工作,但我试图做到这一点在C ++中,所以基本上我想询问是否有与C使用isset()函数的方式++

I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++

PS:这会是与载体更容易?如果是这样,任何人都可以指向我一个很好的载体教程?谢谢

PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks

推荐答案

在C ++中,数组的大小时,它被宣布固定的,而你可以关闭声明数组大小的限制访问,这是很危险的并且难以跟踪下来的错误的来源:

In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:

int i[10];
i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about

看来你要阵列类似的行为,但没有所有元素填充。传统上,这是在哈希表的领域。载体是不是这样一个很好的解决方案在这里你将有空元素占用空间,更好的是像一张地图,在那里如果通过搜索它,跨preting结果中存在的元素,你可以测试:

It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result:

#include <map>
#include <string>

// Declare the map - integer keys, string values    
std::map<int, std::string> a;

// Add an item at an arbitrary location
a[2] = std::string("A string");

// Find a key that isn't present
if(a.find(1) == a.end())
{
   // This code will be run in this example
   std::cout << "Not found" << std::endl;
}
else
{
   std::cout << "Found" << std::endl;
}

警告的一个词:用上面的方法找到,如果一个键存在,而不是像测试一个默认值

One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value

if(a[2] == 0)
{
    a[2] = myValueToPutIn;
}

作为地图的行为是插在该键值的第一次访问一个默认的构造的对象,如果没有当前present。

as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.

这篇关于检查数组索引存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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