• Advertisement
Sign in to follow this  

STL using vecotrs & iterators problem

This topic is 4715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi: I'm trying to make a program that reads a sourcefile and lists all the included files. My problem stems from using an iterator to try and acess an element from a vector in a for loop.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
    string search = "using";
    std::string word;
    vector<string> vs(1);
    int no= 0;
    std::fstream file("main.cpp",std::ios::in);
    while(getline(file,word,'\n'))
    {
        if(word.substr(0,1) == "#")
        {
            vs.push_back(word);
            vs.resize(vs.size()+1);
        }
    }
    cout<<"Showing all includes, using namespaces, and arguments of main"<<'\n';
    for(vector<string>::iterator it = vs.begin(); it < vs.end(); ++it)
    {
        cout<<vs[it]<<"\n";
    }
    std::cin.get();
    return EXIT_SUCCESS;
}

Any help? I get the error: no match for operator[] in vs[it].

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by DigitalDelusion
std::cout << *it; //try this..
Thanks it works! But, can you tell me why I can't use an iterator to speacify an element? Thanks.

Share this post


Link to post
Share on other sites
a iterator is an abstract pointer you simply don't need the container to get the elment since you already have the iterator pointing to it.

what you can do with it though is to tell the container to remove the element the iterator points to and some other nice stuffage :)

Share this post


Link to post
Share on other sites
An iterator is (like) a pointer, not an index. The following for loops are equivalent:
    for(vector<string>::iterator it = vs.begin(); it < vs.end(); ++it)
{
cout << *it << "\n";
}

for(int i = 0; i < vs.size(); ++i)
{
cout << vs << "\n";
}

Share this post


Link to post
Share on other sites
Quote:
Original post by DigitalDelusion
a iterator is an abstract pointer you simply don't need the container to get the elment since you already have the iterator pointing to it.

what you can do with it though is to tell the container to remove the element the iterator points to and some other nice stuffage :)
Ok, must have missed that part in my book, thanks :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement