[英]error: no type named 'vector' in namespace 'std'
Why this is happening? 为什么会这样?
error: no type named 'vector' in namespace 'std'; 错误:命名空间'std'中没有名为'vector'的类型; did you mean 'hecto'? 你是说'百科'吗? void askForVector(std::vector * vector); 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";
}
vector
is a template, not a type. vector
是一个模板,而不是一个类型。 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 eg vector<int>
in the function signature vector是一个模板,而不是一个类型,你需要模板参数列表,例如函数签名中的vector<int>
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.