为什么会这样?
错误:命名空间'std'中没有名为'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";
}
答案 0 :(得分:11)
vector
是模板,而不是类型。指定特定的专业化:
void askForVector(std::vector<int> * vector);
或使函数通用
template <typename T>
void askForVector(std::vector<T> * vector);
使用引用而不是指针可能会更好:
void askForVector(std::vector<int> & vector);
或按值返回向量:
std::vector<int> askForVector() {
std::vector<int> vector;
// your code here
return vector;
}
避免错误,如
std::cin >> vector[i]; // should be (*vector)[i]
答案 1 :(得分:4)
有很多问题:
vector是一个模板,而不是一个类型,你需要模板参数列表,例如函数签名中的vector<int>
由于您传递了一个指向矢量的指针,因此您需要在之前使用下标运算符取消引用它
std::cin >> vector[i]; // wrong
std::cin >> (*vector)[i]; // correct
以下可行:
#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";
}