how do i read 2 consecutive values in vector and compute?

This is a discussion on how do i read 2 consecutive values in vector and compute? within the C++ Programming forums, part of the General Programming Boards category; hey, im new to c++ well actually been working with it for the past two months and i ran into ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    6

    how do i read 2 consecutive values in vector and compute?

    hey, im new to c++ well actually been working with it for the past two months and i ran into problem.

    basically im trying to write a function to read two consecutive values in a vector (they happen to be distances) and calculate the speed at which object is moving and create a new vector with the speeds obtained. im fairly new to C++ and in no way an expert. i can't figure out how to read the first 2 values...do my calculation then output it another vector and repeat.

    anyone provide me with any help?

    if this helps i wrote this function to read a data file and place objects into a vector. it is THIS vector i need to read to find out the speed of objects. btw Speed[0] = ( Dist[1]-Dist[0] )*(3600/15) is equation for speed if you really want to overachieve

    Code:
    void readdatafile(vector<double> &Data, string filename)
    {
    	ifstream fin;
    	fin.open(filename.c_str());
    	// Open file and error check
    	if ( fin.fail() ) // open failed
    	{
    		cout << "The file could not be opened\n";
    	}
    	else
    	{
    		char* Firstline = new char[];
    		fin.getline(Firstline, 20);
    		double X = 0;
    		fin >> X;
    		while( X >= 0)
    		{
    			Data.push_back(X);
    			fin >> X;			
    		}
    	}
    	return;
    
    }
    Last edited by dalearyous; 03-29-2006 at 05:40 PM.

  2. #2
    Master of Puppets rwmarsh's Avatar
    Join Date
    Feb 2006
    Location
    Texas
    Posts
    96
    declaire an iterater for your data vector and two temporary float variables. Then, using the irerater to point to the first value, make the first temp variable equal to what the iterater points to. advance the interater to the next value using '<iterater name>++' and do it all over again. Then you can do whatever calculations you need to the variables.
    look here to learn about iteratershttp://www.cprogramming.com/tutorial/stl/iterators.html


    I hope this makes at least a little sense, I am about half asleep right now.....
    Using DEV-C++ Under Windows XP
    +------------------------------+

    "No! Do, or Do Not. There is no Try..."

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    6
    thanks for your advice. i found chapter in this c++ book i have about iterators and read the page you sent me to but to be honest i don't quite understand it. do you know where i could find more code examples? i just don't have enough experience to figure that out without more examples or help

  4. #4
    Master of Puppets rwmarsh's Avatar
    Join Date
    Feb 2006
    Location
    Texas
    Posts
    96
    An Iterator is nothing more that a pointer. A special one that points to the different fields in a vector. BY using the iterator you can access the different fields in the vector.
    FOr example, you can declair an vector of integers like this
    Code:
    vector<int> MyVector;
    You already know how to populate the vector using the .pushback function. You can then go through all the values in the vector like this
    Code:
    // declaire an iterator for MyVector
    vector<int>::iterator MyIterator;
    
    // display all the values in MyVector
    for (MyIterator=MyVector.begin(); MyIterator!=MyVector.end(); MyIterator++)
        cout<<*MyIterator<<endl;
    This will make MyIterator point to the first value in MyVector ( MyVector.begin() ) and display what it points to. Each pass through the for loop will advance MyIterator to the next value in MyVector ( MyIterator++ ). It does this until MyIterator points to the last value ( MyVector.end() ) then exits the loop. Note that the .end() call means that the iterator points to the first empty field past the last value, not the value itself.
    Instead of using the for loop like that you can also do something like this
    Code:
    for (int x=3; x<=6; x++)
        cout<<MyVector.at(x)<<endl;
    This will display the contents of MyVector at position 3, 4, 5 and 6 only, instead of going through all of them... If those were the only values you wanted to retrieve from the vector.

    I hope this helps to clear up a few things for you. Let me know If you need any more help and I'll see what I can do.
    Using DEV-C++ Under Windows XP
    +------------------------------+

    "No! Do, or Do Not. There is no Try..."

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    6
    is there anything wrong with doing it this way:

    Code:
    x = Data.back();
    Data.pop_back();
    y = Data.back();
    speed = (x - y) * (3600/15);
    that way you plug this into a loop and run it until vector ends. this should have the following effect right?

    like if u have 1,2,3,4,5 it would do x=5 y =4 do speed calc (send answer speed to vector, uh thats not written yet) ...dump x and you would have 1,2,3,4 then run again etc...

  6. #6
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    But you can access vectors w/o using iterators. In some instances , such as removing items from a vector, you must use an iterator. Most others you can access them like an array.

    Code:
    class FooMgr;
    class Foo
    {
      friend class FooMgr; 
      protected:
        int m_iSize;
        unsigned int *m_pArray;
    
      private:
        Foo():m_iSize(0),m_pArray(NULL) { }
        Foo(const Foo &);
        Foo &operator =(const Foo &);
    
        void Destroy(void)
        {
           //For msvc 6 - '03,'05 do not suffer from this issue
           if (m_pArray)
           {
              delete [] m_pArray;
              m_pArray=NULL;
           }
        }
       
        bool Create(int iSize)
        {
           m_pArray=new int[iSize];
           if (!m_pArray)
           {
             return true;
           } else return false;
        }
    
        bool GetValue(int iOffset,int &ioutValue)
        {
           if (iOffset>m_iSize) return true;
    
           iOutValue=m_pArray[iOffset];
           return false;
        }
    
        bool SetValue(int iOffset,int iValue)
        {
          if (iOffset>m_iSize) return true;
          
          m_pArray[iOffset=iValue;
          return false;
        }
    
        unsigned int GetSizeOfArray() {return m_iSize;}
    };
    
    class FooMgr
    {
      private:
        std::vector<Foo *> FooVector;
        FooMgr(const FooMgr &);
        FooMgr &operator=(const FooMgr &);  
      public:
        FooMgr() { }
        ~FooMgr() { }
    
        void Destroy(void)
        {
           for (unsigned int i=0;i<FooVector.size();i++)
           {
              if (FooVector[i]) delete FooVector[i];
           }
    
           FooVector.clear();
         }
    
         bool GetValue(unsigned int uID,int iOffset,int &iOutValue)
         {
            if (iOffset>FooVector[uID]->GetSizeOfArray()) return true;
    
            iOutValue=FooVector[uID]->GetValue(iOffset,iOutValue);
            return false;
         }
    
         .....
    };
    This makes vectors very easy to use and great for resource managers.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    i found chapter in this c++ book i have about iterators and read the page you sent me to but to be honest i don't quite understand it.
    An "iterator" is something that represents a position in a container. Although it's not exactly correct, you can think of an iterator as a pointer to an element in a container. Hopefully, you know what a pointer is--otherwise all is lost. Then it's just a matter of learning the syntax, which can look a bit frightening, but which is actually fairly easy.

    So, let's say you declare a vector and add some elements to the vector, like so:
    Code:
    vector<int> myVec;
    
    for(int i = 0; i<10; ++i)
    {
    	myVec.push_back(i);
    }
    Now, you want to output the elements of the vector using an iterator/pointer. First, you have to declare what type of container the iterator/pointer is going to be pointing to. In this case, we want to use an iterator/pointer that points to a vector of int's:

    vector<int>

    Then you add the member access operator '::',

    vector<int>::

    Next, you specify the type of iterator you want to use. The simplest iterator is one that allows you to both read and write the vector(just like a normal pointer allows you to both access the value and change the value it points to). The name of such an iterator is simply "iterator" (vs. "const_iterator" which only allows you to read the value it points to, not change it):

    vector<int>::iterator

    That piece of code specifies the type of the variable you are going to declare--the variable will be a read/write iterator that points to a vector of ints. Now, you need a variable name. How about 'pos' for "position":

    vector<int>::iterator pos;

    That declares a variable called 'pos' of the specified type. Now you can store an iterator that points to a vector of ints in the variable pos.

    Finally, you need to create one of those strange, alien iterators to store in your variable 'pos'. Luckily, we don't have to worry about creating an iterator because all the STL containers have a begin() and end() member function which will create and return an iterator that points to the first or last element respectively. So, you can do this:

    vector<int>::iterator pos = myVec.begin();

    The result of that statement is that 'pos' will point to the first element in the vector. If you want to "iterate" through all the elements of a vector element by element, you just use '++' on pos to move it from element to element. Therefore, you can use a for-loop to step through all the elements of a vector. To end the for-loop, you can use myVec.end() as the ending condition:
    Code:
    vector<int>::iterator pos; 
    
    for(pos = myVec.begin(); pos != myVec.end(); ++pos)
    {
    	cout<<*pos<<" ";
    }
    cout<<endl;
    A couple of points about that loop:

    1) end() returns a pointer to one past the last element
    2) Use ++pos rather than pos++ because it's more efficient.
    3) Since pos is like a pointer to the element, you need to dereference it to get the actual value.
    4) When you output a vector's contents, you don't need to change the vector, so it would be better to use
    a const_iterator:

    Code:
    vector<int>::const_iterator pos = myVec.begin();
    for(; pos != myVec.end(); ++pos)
    {
    	cout<<*pos<<" ";
    	/*pos = 10;  error*/
    }
    cout<<endl;
    is there anything wrong with doing it this way:
    Code:
    x = Data.back();
    Data.pop_back();
    y = Data.back();
    speed = (x - y) * (3600/15);
    that way you plug this into a loop and run it until vector ends.
    No--except there's no reason to remove each element from the vector, so it's inefficient.
    Last edited by 7stud; 03-30-2006 at 08:33 AM.

  8. #8
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    7stud, that's a really good post. someone should sticky it, or add it to the faq.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,324
    >> Hopefully, you know what a pointer is--otherwise all is lost.

    Except for that part. When learning C++ there's nothing wrong with knowing iterator concepts and syntax before learning about pointers.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21