How to extract an element from Vector

Posted on 2013-10-09
Medium Priority
Last Modified: 2013-10-10
I try to extract the element in the for loop and I get an error.
Error C2440: 'initializing' : cannot convert from 'std::_Vector_const_iterator<_Myvec> *' to 'item'

Below is the code, it complain this particular line:-itemEntry it = &j; in the for loop
      typedef struct item
            item(int n) : X(n) { }
            int X;
        itemEntry;std::vector <itemEntry> itemList;
      std::vector<itemEntry>::const_iterator j;      
      itemEntry *it;
      it = new itemEntry(1);
      itemList.push_back (*it);
      it = new itemEntry(2);
      itemList.push_back (*it);

      for (j = itemList.begin(); j != itemList.end(); ++j)
            itemEntry it = &j; // This causes an syntax error, I like to exract out and manipulate the content
            std::cout << j->X << std::endl;

How do I correct this problem
Question by:tommym121
LVL 86

Accepted Solution

jkr earned 2000 total points
ID: 39560458
That seems to be a simple typo, that line has to be

itemEntry it = *j; // '*', not '&'

Open in new window


Author Closing Comment

ID: 39560705
LVL 29

Expert Comment

ID: 39561419
If there is any chance your compiler can or your project is allowed to use C++11 features, go for it. The new for loops and auto are a big enhancement, in my opinion. The loop would look like:
for (const auto &item: itemList)
    cout << item.X << endl;

Open in new window

LVL 40

Expert Comment

ID: 39561601
+1 for pepr's recommendation!

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

619 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question