Software & Finance





Visual C++ STL Using Vector - adding items, index based access and iterator





Here is the sample code for STL Vector of strings. The string is nothing but a collection of filenames in a directory.

 

We can do two types of accessing in vector. The first one is index based accessing by using index operator []. The next method is using iterator or const_iterator. The iterator it != list.end() represents, whether we reached the end of the vector or not. ++it (preincrement is faster) refers to move to next item. The content of it (*it) or (it->) represents the actual element.

 

#include <string>

#include <vector>

#include <windows.h>

 

// searchkey = "c:\\kathir\\*.txt";

int GetFileList(const char *searchkey, std::vector<std::string> &list)

{

    WIN32_FIND_DATA fd;

    HANDLE h = FindFirstFile(searchkey,&fd);

 

    if(h == INVALID_HANDLE_VALUE)

    {

        return 0; // no files found

    }

 

    while(1)

    {

        list.push_back(fd.cFileName);

 

        if(FindNextFile(h, &fd) == FALSE)

            break;

    }

    return list.size();

}

 

 

void main()

{

    std::vector<std::string> list;

    int count = GetFileList("c:\\kathir\\*.txt", list);

 

    // Using Index Based Accessing

    for(int i = 0; i < list.size(); i++)

        MessageBox(list[i].c_str());

 

    // Using const_iterator

    for(std::vector<std::string>::const_iterator it = list.begin();

        it != list.end(); ++it)

    {

        MessageBox(it->c_str());

    }

}