简体   繁体   中英

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 .

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;

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 .

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 (ie, 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;
   }
}

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 thsi iterator you can traverse all elements and perform respective operation like remove element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM