Home > Software design >  How to use a vector in a vector
How to use a vector in a vector

Time:10-02

I am trying to use a for statement with a vector in a vector.

std::vector<std::string> array = {
    {"A", "a"},
    {"B", "b"},
    {"C", "c"}
};

for (std::string& a : array) {
    if (letter == a[1] || letter == a[0]) {
        std::cout << a[0] << ": " << a[1] << std::endl;
        break;
    }
}

I am new to C and cannot figure out why it gives me errors about this.


Edit:

Error: error: invalid operands to binary expression ('std::string' (aka 'basic_string<char>') and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char'))

CodePudding user response:

I think {"A", "a"} is already a verctor, and this array varable type should be vector<vector<string>>.

CodePudding user response:

The problem is in how you initialize your strings. The following fails as well:

std::string s {"A", "a"};

"A" and "a" are of type const char* and represent two characters each (the letter, and a null terminator '\0').

What you probably want is to initialize your strings with char elements instead:

std::vector<std::string> array = {
    {'A', 'a'},
    {'B', 'b'},
    {'C', 'c'}
};

Note the single quotes '. You can also just do this:

std::vector<std::string> array = {
    "Aa",
    "Bb",
    "Cc"
};
  •  Tags:  
  • c
  • Related