Check if array index exists

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

I usually work with php, but I try to do it in C ++, so basically I try to ask if there is isset () way to use with C ++

PS: Will it be easier with vectors? If so, can someone point me to a good vector tutorial? Thanks

+3
source share
4 answers

In C ++, the size of the array is fixed when it is declared, and although you can access the end of the declared size of the array, this is very dangerous and is a source of hard tracking errors:

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

, , . -. , , , , , , , :

#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;
}

: , , , -

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

, , .

+8

. , - (, , ), .

, , , google search

+3
+1

, , , . : if(index < array_size) .

If you don’t know the size, you can find it using the operator sizeof.

For instance:

int arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int arr_size = sizeof(arr)/sizeof(arr[0]);
+1
source

Source: https://habr.com/ru/post/1699015/


All Articles