简体   繁体   English

如何从std :: vector <>正确初始化向量

[英]How to properly initialize a vector from std::vector<>

When I compile the following code (using the -std=c++11 compiler flag), I get the (only) error message: " 'vec' is not a class, namespace or enumeration". 当我编译以下代码(使用-std = c ++ 11编译器标志)时,我得到(仅)错误消息:“'vec'不是类,命名空间或枚举”。

#include <vector>
#include <iterator>

int main(){

std::vector<int> vec(10,1);
vec::iterator it;

return 0;
}

As I do not get any other error message, to me this means that some object called 'vec' has been initialized, but not as a vector, but as something else which is not a class and for which the scope operator can therefore not be used. 由于我没有得到任何其他错误消息,对我来说这意味着一些名为'vec'的对象已经初始化,但不是作为向量,而是作为其他不是类的东西,因此范围运算符不能用过的。

As far as I understood it, I used the following constructor ( http://en.cppreference.com/w/cpp/container/vector/vector ): 据我所知,我使用了以下构造函数( http://en.cppreference.com/w/cpp/container/vector/vector ):

vector(size_type count,
       const T& value,
       const Allocator& alloc = Allocator());

Where it says that this constructor "Constructs the container with count copies of elements with value value", so I expect to have created a vector with 10 copies of "1", but I must have misunderstood something, hence the problem. 如果它说这个构造函数“使用值值的元素的计数副本构造容器”,那么我希望创建一个包含10个副本“1”的向量,但我必须误解一些东西,因此问题。

Where did my reasoning go wrong and where does the error in the above code stem from? 我的推理在哪里出错了,上面代码中的错误源自何处?

Your initialization of the vector is fine. 你初始化矢量很好。 But in order to refer to the iterator type, you need to use the vector's type and not an object: 但是为了引用迭代器类型,您需要使用向量的类型而不是对象:

std::vector<int>::iterator it;

The scope operator is used for accessing elements within a namespace or class. 范围运算符用于访问命名空间或类中的元素。 vec isn't a class but an object. vec不是一个类,而是一个对象。 You have to write std::vector<int>::iterator . 你必须编写std::vector<int>::iterator You could also deduce a type of a variable by using auto: auto it = vec.begin() equals to std::vector<int>::iterator it = vec.begin() 您还可以使用auto来推断变量的类型: auto it = vec.begin()等于std::vector<int>::iterator it = vec.begin()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM