Accessing a string vector's entries

I am taking a string message chopping it up and then building a vector out of the chopped up messages. But I am wondering how do I access the vector's entries? I have tried String accessp = str.at(1); and String & element = str[1]; for example and am getting compilation errors. Does anyone know what I am doing wrong?

#include <iostream>
#include <string>
#include <vector>
     
std::vector<std::string> str;

void setup(){
    std::string s = "scott>=tiger>=mushroom>=fail";
    std::string delimiter = ">=";
    
    size_t start = 0, pos;
    std::string token;

    while ((pos = s.find(delimiter, start)) != std::string::npos) {
        token = s.substr(start, pos-start);
        str.push_back(token);
        start = pos + delimiter.size();
    }
    if (start < s.size())
        str.push_back(s.substr(start));

    for(auto &elem : str)
        std::cout << elem << std::endl;
}

void loop(){
  
}

std::vector overloads operator[]. So, you can use array-type access.

1 Like

It seems to access the first entry in the vector, the correct method for me to use is

std::string element = str.at(0);

You can simply use:

element[0];

to access the same element of the vector.

operator[] does not perform bounds checking, function at() does. Other than that they do the same thing.

But, since Arduino environments don't typically implement exceptions, I'm not sure what the result of an out-of-bounds check will be.

What error are you getting?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.