Search code examples
c++visual-c++iterator

How to fill an unknown sized vector using iterators?


I'm trying to create a graph in which I don't know its size , the user fill the vector until user wants. and how can I get the elements using iterators?

my code which is not completed :

#include <iostream>
#include <vector>
#include <iterator>
#include <list>

void main(void)
{
    {
        using namespace std;
        
        vector<vector<char>> graph;
        vector<vector<char>>::iterator outerMove;
        vector<char>::iterator innerMover;
        cout << "enter your verteces name one by one and write done when you are done";
        for (outerMove = graph.begin(); outerMove != graph.end(); ++outerMove)
        {
            //first get the size of vector , how much user wants enters 
        }
        for (innerMover = )
        {
            //now here graph.push_back(innerMove) 
        }
}

thanks for the help.


Solution

  • You don't use iterators in this case, you use push_back and let the vector do its job (that is, resize automatically):

    vector<std::string> graph;
    std::string outermove;  // a proper "list of chars"!
    
    while ((cin >> outermove) && outermove != "done")
        graph.push_back(outermove);
    

    Unrelated to the question:

    void main() is illegal in C++, main needs to return int. (void) is a C way of writing an empty parameter list - in C++ it's simply ().