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";
}
Vectors in C++C++ has a vector class within the std namespace. A vector is similar to an array, in a sense where a series of elements are stored with the same variable name. Unlike arrays, vectors are dynamically sized, which is a major advantage.
1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.
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]
There are multiple issues:
vector is a template, not a type, you need the template argument list e.g. vector<int>
in the function signature
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With