Home > Back-end >  c error: why this error shows " expected type specifier in vector "
c error: why this error shows " expected type specifier in vector "

Time:01-13

I include the vector but when I declare a vector inside the class it shows an error(expected type specifier) do my code is correct?

#include <vector>
#include <string>
class Ecole {

    vector<string> arr(10);
};

CodePudding user response:

As other answers already mentioned, you will need to write the namespace std infront of vector and string.

Also I would assume that you will have to initialise the variable like this:

std::vector<std::string> arr = std::vector<std::string>(10);

As you cannot initalise it with just (10) directly inside of the class. (Outside of a method)

CodePudding user response:

I bet it would work if you replace <string> with <std::string> and replace <vector> with <std::vector>

The issue is that string is included in the std namespace, so it must be addressed accordingly.

Another way to make it work is to add

using namespace std;

...above the class declaration, although it is said to be bad practice, as described here: https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/

CodePudding user response:

The vector and string are declared in the namespace std, So use the namespace to refer them.

#include <vector>
#include <string>
class Ecole {

    std::vector<std::string> arr(10);
};

If you want to get the rid of using std each time, you can write using namespace std; before the class declaration;

#include <vector>
#include <string>
using namespace std;
class Ecole {

    vector<string> arr(10);
};

But this is the bad idea, see the link Why is "using namespace std;" considered bad practice?

The other problem is that you are trying to initialise arr(10) the vector without the referring to any variable in the class directly, you have to declare and initialisation both in the class.

class Ecole {

    std::vector<std::string> arr = std::vector<std::string>(10);
};

And if you want to declare and then initialise in the constructor.

#include <vector>
#include <string>
class Ecole {
    
    std::vector<std::string> arr;
    
    Ecole(){
        this->arr = std::vector<std::string>(10);
    }
    
};

If you want to just play with the vector without the class, you can use directly in the main function.

#include <vector>
#include <string>
int main() {
    std::vector<std::string> arr(10);
    // start playing here

    return 0;
}
  •  Tags:  
  • Related