Eric
Eric

Reputation: 109

How to tell if a vector has a certain number of elements C++

I wouldn't be surprised if this is a duplicate but I've searched all around and have only found posts on finding specific elements in vectors.

I have a code that splits a string into a vector of all the individual words in the string (split by spaces) and later assigns each index of that vector to individual strings (so just taking a sentence and splitting it up into words) but I found if I try to index a certain element of the vector that doesn't exist I get all sorts of errors. For example, if my vector has 5 elements and later I say:

string x = names[6];

then, since there is no names[6], the code breaks. I want to add an "if" statement that essentially says "if names[6] exists, string x = names [6]" but I don't know how to check if names[6] (or any other index of the vector) exists.

I have tried:

    if (std::find(names.begin(), names.end(), names[4]) != names.end()) 
    {
        string x = names[4];
    }
    else 
    {
    }

but I end up with the same errors if names[4] doesn't exist.

If someone could please let me know how to do this or reference me to another post that explains this that would be great,

-thanks

Upvotes: 0

Views: 375

Answers (2)

Floris Velleman
Floris Velleman

Reputation: 4888

What about putting all the entries of the vector into strings by iterating them?

for (const auto& e : names) {
    // You can use e here 

}

If you really want to check if an index exists you could check with at:

try {
   std::string x = names.at(position);
}
catch (const std::out_of_range& oor) {
   //Nothing at this spot!
}

You could also check with vector.size().

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50053

An index in an std::vector exists iff index < vector.size(). You may test for that:

if (names.size() > 4)
    string x = names[4];

Upvotes: 3

Related Questions