0

I just read about vectors in C++. They seem to be like lists in Python, but they can only take values of the datatype specified in the declaration. For example:

vector<int> intlist;

Takes only int type data. Whereas a list in Python take any type of data. I tried to implement the same in C++ by writing:

vector<auto> list;

But it resulted in an erroneous compilation. I am not sure why this happens as it works fine with other datatypes.

いちにち
  • 417
  • 6
  • 16

3 Answers3

2

auto is not a variant type, it is simply a shortcut you can use in your code when the type can be deduced by the compiler.

Underneath a Python list is some implementation of a variant and I would suggest using boost::python to manage C++ - Python interaction.

CashCow
  • 30,981
  • 5
  • 61
  • 92
2

You're doing it the wrong way.

C++ is strong typed. auto is a keyword used when the type of variable can be determined at compile time, that's not what you want.

If you need to have a vector of object of different types, you must use some library like boost::any.

EDIT:

C++ is statically typed and Python dinamically typed, this is the difference. Thanks to @Angew for correcting my mistake.

Jepessen
  • 11,744
  • 14
  • 82
  • 149
1

Also, if this is something you really want to achieve in c++ I recommend switching to c++17 and using std::variant. This is an example of using std::variant which at face-value may seem somewhat similar to a python array.

#include <variant>
#include <iostream>
#include <string>

using my_variant = std::variant<std::string, float, int, bool>;
int main(){
    std::vector<my_variant> list = {"hello", 5.0, 10.0, "bye", false};
    for(int i = 0; i < list.size(); i++){
         std::visit([](auto arg){std::cout<<arg<<std::endl;}, list.at(i));
    }
    return 0;
}
Sam Moldenha
  • 463
  • 2
  • 11