Lidia Freitas
Lidia Freitas

Reputation: 334

error: no type named 'vector' in namespace 'std'

Why this is happening?

error: no type named 'vector' in namespace 'std'; did you mean 'hecto'? void askForVector(std::vector * vector);

#include <iostream>
#include <vector>

void askForVector(std::vector * vector);

int main()
{
    std::vector<int> vector;
    int size;
    askForVector(&vector);
    std::cout << "\nsize: " << vector.size() << std::endl;
    std::cout << vector.at(0);
}


void askForVector(std::vector * vector)
{
    int size;
    std::cout << "please insert the size of vector to order: ";
    std::cin >> size;

    vector->resize(size);

    for(int i = 0; i<size; i++){
        std::cout <<  "please insert a value for the " << i+1 << " position: " ;
        std::cin >> vector[i];
    }

    for(int j: *vector)
        std::cout << ":"<<j;
    std::cout  << ":\n";
}

Upvotes: 16

Views: 34597

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254691

vector is a template, not a type. Either specify a particular specialisation:

void askForVector(std::vector<int> * vector);

or make the function generic

template <typename T>
void askForVector(std::vector<T> * vector);

You might be better off using a reference rather than a pointer:

void askForVector(std::vector<int> & vector);

or returning the vector by value:

std::vector<int> askForVector() {
    std::vector<int> vector;
    // your code here
    return vector;
}

to avoid errors like

std::cin >> vector[i]; // should be (*vector)[i]

Upvotes: 15

Marco A.
Marco A.

Reputation: 43662

There are multiple issues:

  1. vector is a template, not a type, you need the template argument list e.g. vector<int> in the function signature

  2. Since you're passing a pointer to a vector you need to dereference it before using the subscript operator

    std::cin >> vector[i]; // wrong
    std::cin >> (*vector)[i]; // correct
    

The following could work:

#include <iostream>
#include <vector>

void askForVector(std::vector<int> * vector);

int main()
{
    std::vector<int> vector;
    int size;
    askForVector(&vector);
    std::cout << "\nsize: " << vector.size() << std::endl;
    std::cout << vector.at(0);

}


void askForVector(std::vector<int> * vector)
{
    int size;
    std::cout << "please insert the size of vector to order: ";
    std::cin >> size;

    vector->resize(size);

    for (int i = 0; i<size; i++){
        std::cout << "please insert a value for the " << i + 1 << " position: ";
        std::cin >> (*vector)[i];
    }

    for (int j : *vector)
        std::cout << ":" << j;
    std::cout << ":\n";
}

Example

Upvotes: 4

Related Questions