0

I want to initialise a list of lists (as in Python) in C++. Suppose the list is: [['a','b'],['c','d']]

New to C++, and mostly worked in Python so not sure what to do.

std::vector<vector<string>> dp {{'a',b'}};

I have tried this but doesn't seem to work.

no matching function for call to 'std::vector<std::vector<std::__cxx11::basic_string<char> > >::vector(<brace-enclosed initializer list>)'|
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
mayaa
  • 103
  • 5
  • 5
    You need to show the error that you see. – SomeDude Aug 12 '19 at 12:00
  • Please take some time to read [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly don't forget how to create a [mcve]. – Some programmer dude Aug 12 '19 at 12:00
  • 2
    What does your C++ book say about this? – Sam Varshavchik Aug 12 '19 at 12:05
  • 1
    It really looks like you could use [a good book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Aug 12 '19 at 12:11

2 Answers2

11

It looks similar in C++, but string literals should be surrounded by " not ' (which is for character literals).

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::vector<std::string>> dp{{"hello", "world"},
                                             {"goodbye", "for", "now"}};
    for(const auto& v : dp) {
        for(const std::string& s : v) {
            std::cout << s << " ";
        }
        std::cout << "\n";
    }
}

Output:

hello world
goodbye for now
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Oh, I used single quotes! Thanks! – mayaa Aug 12 '19 at 12:12
  • 1
    The single quotes themselves are not an error. For instance, `vector> dp {{'a',b'}, {'c','d'}};` is OK. C++ has stronger typing than Python; your element initializers' type needs to be similar ("convertible") to the container element type. – MSalters Aug 12 '19 at 12:21
  • 1
    @MSalters Yes, but OP needs to be extra careful in this specific case. Char is implicit convertible to int, so if you accidentally mixes notation then it can go wrong without producing an error: `vector dp {'c', "d"}` compiles happily and produces a vector with 99 'd's (since 'c' = to 99 in the ascii table). – Frodyne Aug 12 '19 at 12:40
0

Are you after something like this?

    std::vector<std::vector<std::string>> dp = {
        {"a", "b"},
        {"c", "d"},
        {"e","f"}
    };
Frodyne
  • 3,547
  • 6
  • 16