Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a given index exists in std::vector

I need index access to my std::vector, and therefore I must check if an index is already available to first delete them, and then set a new value.

Here's my setter function:

void SetVector(int position, int value) {
    std::vector<int>iterator it = testVector.begin();
    // need a check here
    testVector.insert(it-testVector.begin()+position, value);
}

Or is this the wrong C++ collection for my needs? (should grow dynamically, so no std:array possible). Could use a std::map but maybe it's also possible with std::vector.

like image 721
leon22 Avatar asked Jul 17 '13 12:07

leon22


3 Answers

I don't believe the question is clear. If you want

"to first delete them, and then set a new value."

this might work

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.

like image 89
doctorlove Avatar answered Oct 19 '22 12:10

doctorlove


The requirements aren't entirely clear from the question, but I'm assuming that you want to end up with testVector[position] == value, whether or not position was in range to begin with.

First grow the vector if it's too small. This will insert zero-values after whatever is already there.

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

Then assign the element you want to set:

testVector[position] = value;
like image 34
Mike Seymour Avatar answered Oct 19 '22 12:10

Mike Seymour


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

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;
   }
}
like image 3
Alexis Avatar answered Oct 19 '22 12:10

Alexis