asked in C plus plus (C++) by (6.6k points) edited by
0 like 0 dislike
7 views

I need index access to array/container of type std::vector, and therefore I must check if an index is already available. How I can to check existence a certain index/key in std::vector array in C++ program language?

check if a given index exists in std::vector
c++ vector check if index exists

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

0 like 0 dislike
answered by (6.6k points) edited by

You can do it something like this:

if (position >= testVector.size()) {
	testVector.resize(position + 1);
}
testVector[position] = value;

Function for it:

void setVector(int position, int value) {
	if (position < testVector.size()) {
		testVector[position] = value;
	} else {
		testVector.push_back(value);
	}
}

You should really make the int position the testVector's size_type.


You can use std::vector::at who throw an exception if you don't have anything at this index.

The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not, i.e., if n is greater or equal than its size. This is in contrast with member operator [], that does not check against bounds.

And since you get a reference on the object at the given index, you can change/delete the value.

Realization of function via try-catch construction:

void setVector(int position, int value) {
	try {
		testVector.at(position) = value;
	} catch (const std::out_of_range& oor) {
		testVector.resize(position + 1);
		testVector[position] = value;
   }
}

Use iterator. First get an iterator for your vector by using:

std::vector<int>::iterator it;
it = myvector.begin();
for (it = myvector.begin(); it < myvector.end(); it++)
	 std::cout << ' ' << *it;

Using this iterator you can traverse all elements and perform respective operation like remove element.

Links

Related questions

0 like 0 dislike
1 answer 25 views
0 like 0 dislike
1 answer 32 views
0 like 0 dislike
1 answer 14 views
0 like 0 dislike
1 answer 8 views
0 like 0 dislike
1 answer 16 views
0 like 0 dislike
1 answer 16 views
0 like 0 dislike
1 answer 307 views
0 like 0 dislike
1 answer 52 views
0 like 0 dislike
1 answer 16 views
0 like 0 dislike
1 answer 5 views
...