简体   繁体   中英

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".

#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.

As far as I understood it, I used the following constructor ( 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.

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. You have to write 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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