kevin29
kevin29

Reputation: 99

Looping through all characters in a string element of a string vector in C++

Say, for example I have a vector. The vector contains i items. Say I want to loop through all positions j in every element i of the vector. I attempt to use a nested for loop to perform the procedure in the following code. It attempts to change every element to all ks, like so:

vector<string> strvec;
strvec.push_back("Dog");
strvec.push_back("Cat");

for (int i = 0; i < strvec.length; i++)
{
    for (int j = 0; j < strvec[i].length; j++)
    {
        strvec[i][j] = 'k';
    }
}

Whenever using the loop in this manner, the above code will get error messages, even before the code in the nested loop (starting at the beginning of the nested loop). Is there a way to loop through every character in every element of a string vector that is effective and that works?

Upvotes: 1

Views: 2842

Answers (2)

Marshall Clow
Marshall Clow

Reputation: 16670

std::vector has a size function you can use for iteration:

for (std::size_t i = 0; i < strvec.size(); i++)
{
    for (std::size_t j = 0; j < strvec[i].size(); j++)
    {
        strvec[i][j] = 'k';
    }
}

Upvotes: 2

user4581301
user4581301

Reputation: 33931

Here is an approach that uses references and range-based for. Any time you have to iterate a container starting at the beginning, try range-based for first. It's not as versatile as manual control, but it is really, really hard to get wrong.

for (string & str: strvec)
{
    for (char & ch: str)
    {
        ch = 'k';
    }
}

Upvotes: 2

Related Questions