It is currently Tue Dec 12, 2017 6:35 pm




 Page 1 of 1 [ 12 posts ] 
Author Message
 Post subject: Need help with std::vector
PostPosted: Tue Jan 05, 2010 3:08 pm 

Joined: Sat Apr 19, 2008 6:26 am
Posts: 62
Hello.

I try create code like this and linker error


#include <string>
#include <iostream>
#include <vector>

class a{
// contructo, destructor, functions etc
public:
....
vector<string> s_vnameProf;
vector<string> s_vdirNamePath(string dirname, string ext = "");
...
};



and where in cpp



//(this line is error)
s_vnameProf= s_vdirNamePath(getPathDir(), ".prof");


// getPathDir() return string (like this game/prof/name)


try compile ( OK ) error linker
error LNK2001: unresolved external symbol "public: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct .......



What is wrong - it's missing something. How to assign a "vector <string> = vector <string>"


Offline
 Profile  
 
 Post subject:
PostPosted: Wed Jan 06, 2010 2:15 am 

Joined: Fri Sep 04, 2009 3:24 am
Posts: 30
The '=' is overloaded for vectors, as in a = b.

Your trying to assign a string to a vector as in, a = "I'm a string"
a is of type vector, not string. It can store strings, but isn't one.

You should be using insert, assign or push_back to add to a vector.

Check out: http://www.cplusplus.com/reference/stl/vector/


Offline
 Profile  
 
 Post subject:
PostPosted: Mon Jan 11, 2010 12:02 pm 

Joined: Sat Apr 19, 2008 6:26 am
Posts: 62
OK.
#include <string>
#include <iostream>
#include <vector>

class a{
// contructor, destructor, functions etc
public:
....
vector<string> s_vnameProf;
vector<string> s_vdirNamePath(string dirname, const string ext = "");
...
};



vector<string> s_vdirNamePath(string dirname, const string ext)
{
    char nameFileInDirectory[261];
    vector<string> ret;
 
     .....

    ret.push_back(nameFileInDirectory);

    return ret;
};


//and use this code
s_vnameProf= s_vdirNamePath(getPathDir(), ".prof"); <- now is fine

vector<string> = vector<string> :wink:


Offline
 Profile  
 
 Post subject: Re: C++ VMK 10 - Standard Template Library
PostPosted: Fri Aug 24, 2012 4:59 am 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 450
I am working on a small project and doing some stuff with polygon algebra, and I have a custom data struct that looks like this...
   struct Term {
      unsigned int   _uiTermIndex;
      float         _fCoefficient;
      float         _fExponent;   
      char         _cIndependentVariable;
      char         _cCoefficientSign;
      char         _cExponentSign;

      Term(){}
      Term( float fCoefficient, char cVariable, float fExponent ) :
        _fCoefficient( fCoefficient ),
        _cIndependentVariable( cVariable ),
        _fExponent( fExponent ) {

         if ( _fCoefficient > 0 ) {
            _cCoefficientSign = '+';
         } else if ( _fCoefficient < 0 ) {
            _cCoefficientSign = '-';
         } else if ( _fCoefficient == 0 ) {
            _cCoefficientSign = ' ';
            _cIndependentVariable = ' ';
            _cExponentSign = ' ';
            _fExponent = 0;
         }

         if ( _fExponent > 1 ) {
            _cExponentSign = '+';
         } else if ( _fExponent < 0 ) {
            _cExponentSign = '-';
         } else if ( _fExponent == 1 ) {
            _cExponentSign = ' ';
         }
      } // Term

   }; // Term

This struct is a private to a class and the class contains a private vector<Term> _vTerms.

I am writing a few functions in the class where I am trying to combine like terms and order the vector<Terms> by degree of exponent. I tried using for loops, while loops conditionals and im getting stuck. Would I be better off using iterators, or using recursion? Any bit of help would be great.


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sat Aug 25, 2012 11:00 am 
Site Admin

Joined: Sun Feb 11, 2007 8:59 am
Posts: 1105
Location: Ontario Canada
use the stl sort function with a custom operator() that compares the exponent: http://www.cplusplus.com/reference/algorithm/sort/

bool operator() (Term a, Term b) {
   return ( a._fExponent < b._fExponent);
}


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sat Aug 25, 2012 7:18 pm 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 450
ah ok, I was using the sort function, but never overloaded the operator.


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sat Aug 25, 2012 10:02 pm 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 450
ok, I have overloaded the operator and written the function my class will do, this is the code for the function and for the operator:
// ------------------------------------------------------------------------- //
// setPolynomialByDegreeOfExponent()
//
void Polynomial::setPolynomialByDegreeOfExponent() {
   
   unsigned int uiIndex = _uiNumTerms - 1;
   if ( uiIndex <= 1 ) {
      return;
   }   

   while ( uiIndex > 1 ) {
      sort( _vTerms[uiIndex]._fExponent, _vTerms[uiIndex-1]._fExponent );
      uiIndex--;
   }


} // setPolynomialByDegreeOfExponent


// ------------------------------------------------------------------------- //
// operator()
//
bool Polynomial::operator() ( Term a, Term b ) {

   return ( a._fExponent < b._fExponent );

} // operator()


I seem to be running into this error from visual studio:

1>------ Build started: Project: AdvancedMathematics, Configuration: Debug Win32 ------
1> Polynomial.cpp
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(373): error C2825: '_Iter': must be a class or namespace when followed by '::'
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(728) : see reference to class template instantiation 'std::iterator_traits<_Iter>' being compiled
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(3641) : see reference to function template instantiation 'void std::_Debug_range<_RanIt>(_InIt,_InIt,std::_Dbfile_t,std::_Dbline_t)' being compiled
1> with
1> [
1> _RanIt=float,
1> _InIt=float
1> ]
1> c:\users\skilz80\documents\visual studio 2010\projects\advancedmathematics\polynomial.cpp(152) : see reference to function template instantiation 'void std::sort<float>(_RanIt,_RanIt)' being compiled
1> with
1> [
1> _RanIt=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(373): error C2039: 'iterator_category' : is not a member of '`global namespace''
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(373): error C2146: syntax error : missing ';' before identifier 'iterator_category'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(373): error C2602: 'std::iterator_traits<_Iter>::iterator_category' is not a member of a base class of 'std::iterator_traits<_Iter>'
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(373) : see declaration of 'std::iterator_traits<_Iter>::iterator_category'
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(373): error C2868: 'std::iterator_traits<_Iter>::iterator_category' : illegal syntax for using-declaration; expected qualified-name
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(374): error C2825: '_Iter': must be a class or namespace when followed by '::'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(374): error C2039: 'value_type' : is not a member of '`global namespace''
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(374): error C2146: syntax error : missing ';' before identifier 'value_type'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(374): error C2602: 'std::iterator_traits<_Iter>::value_type' is not a member of a base class of 'std::iterator_traits<_Iter>'
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(374) : see declaration of 'std::iterator_traits<_Iter>::value_type'
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(374): error C2868: 'std::iterator_traits<_Iter>::value_type' : illegal syntax for using-declaration; expected qualified-name
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(375): error C2825: '_Iter': must be a class or namespace when followed by '::'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(375): error C2039: 'difference_type' : is not a member of '`global namespace''
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(375): error C2146: syntax error : missing ';' before identifier 'difference_type'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(375): error C2602: 'std::iterator_traits<_Iter>::difference_type' is not a member of a base class of 'std::iterator_traits<_Iter>'
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(375) : see declaration of 'std::iterator_traits<_Iter>::difference_type'
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(375): error C2868: 'std::iterator_traits<_Iter>::difference_type' : illegal syntax for using-declaration; expected qualified-name
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(377): error C2825: '_Iter': must be a class or namespace when followed by '::'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(377): error C2039: 'pointer' : is not a member of '`global namespace''
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(377): error C2146: syntax error : missing ';' before identifier 'pointer'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(377): error C2602: 'std::iterator_traits<_Iter>::pointer' is not a member of a base class of 'std::iterator_traits<_Iter>'
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(377) : see declaration of 'std::iterator_traits<_Iter>::pointer'
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(377): error C2868: 'std::iterator_traits<_Iter>::pointer' : illegal syntax for using-declaration; expected qualified-name
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(378): error C2825: '_Iter': must be a class or namespace when followed by '::'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(378): error C2039: 'reference' : is not a member of '`global namespace''
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(378): error C2146: syntax error : missing ';' before identifier 'reference'
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(378): error C2602: 'std::iterator_traits<_Iter>::reference' is not a member of a base class of 'std::iterator_traits<_Iter>'
1> with
1> [
1> _Iter=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(378) : see declaration of 'std::iterator_traits<_Iter>::reference'
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(378): error C2868: 'std::iterator_traits<_Iter>::reference' : illegal syntax for using-declaration; expected qualified-name
1> with
1> [
1> _Iter=float
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\xutility(728): error C2665: 'std::_Debug_range2' : none of the 2 overloads could convert all the argument types
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(703): could be 'void std::_Debug_range2<_InIt>(_InIt,_InIt,std::_Dbfile_t,std::_Dbline_t,std::input_iterator_tag)'
1> with
1> [
1> _InIt=float
1> ]
1> c:\program files\microsoft visual studio 10.0\vc\include\xutility(711): or 'void std::_Debug_range2<_InIt>(_RanIt,_RanIt,std::_Dbfile_t,std::_Dbline_t,std::random_access_iterator_tag)'
1> with
1> [
1> _InIt=float,
1> _RanIt=float
1> ]
1> while trying to match the argument list '(float, float, std::_Dbfile_t, std::_Dbline_t, float)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Im not sure why it is giving me this error about the iterators.

Also, I want this algorithm to sort the exponent values from greatest to least from left to right. for example: 3x^2 + 4x^3 would yeild 4x^3 + 3x^2. Also as a note I am working from the back of the container to the front of the container.


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sun Aug 26, 2012 7:30 am 

Joined: Tue Aug 14, 2012 10:41 am
Posts: 10
Location: ShangHai, China
// ------------------------------------------------------------------------- //
// setPolynomialByDegreeOfExponent()
//
void Polynomial::setPolynomialByDegreeOfExponent() {
   
   unsigned int uiIndex = _uiNumTerms - 1;
   if ( uiIndex <= 1 ) {
      return;
   }   

   struct _CompareOperator_ {
      // ------------------------------------------------------------------------- //
      // operator()
      //
     bool operator() ( const Term& a, const Term& b ) {

       return ( a._fExponent < b._fExponent );

     } // operator()

   };

   sort( _vTerms.begin(),  _vTerms.end(), _CompareOperator_());

} // setPolynomialByDegreeOfExponent


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sun Aug 26, 2012 7:36 am 

Joined: Tue Aug 14, 2012 10:41 am
Posts: 10
Location: ShangHai, China
I have heard that the new C++ 11 standard introduces the lambda expression. But I'm not familiar with it. Using lambda expression is more elegant. Sorry.


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Sun Aug 26, 2012 8:18 am 
Site Admin

Joined: Sun Feb 11, 2007 8:59 am
Posts: 1105
Location: Ontario Canada
skilz80 wrote:
Im not sure why it is giving me this error about the iterators.


Here is another reference on how to use the sort function if you still don't understand how it works: microsoft docs


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Mon Aug 27, 2012 5:36 am 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 450
Thank You henrya2 that really helped me alot, although I used stable_sort and was sorting in descending order your method proved usefull. I am able to successfully sort any # of terms in the polynomial by order of degree of our exponent value. The next function I am working on is combining like terms. I am running into a pitfall here. This function calls other functions, and the mehtods work however as the vector is being resized within a for-loop the iterator is going out of bounds in the vector. Here are the functions in use.

addNewTerm()
// ------------------------------------------------------------------------- //
// addNewTerm()
// Adds A New Term To The Polynomial
void Polynomial::addNewTerm( float fCoefficient, char cVar, float fExponent ) {

   Term t( fCoefficient, cVar, fExponent );
   t._uiTermIndex += 1;
   _vTerms.push_back( t );

   resetIndexValues();

} // addNewTerm


removeTerm()
// ------------------------------------------------------------------------- //
// removeTerm()
// Removes The NTH Term From The Polynomial
void Polynomial::removeTerm( unsigned int uiTerm ) {

   if ( uiTerm < 0 ) {
      uiTerm = 0;
   } else if ( uiTerm >= (int)_vTerms.size() ) {
      uiTerm = (int)_vTerms.size() - 1;
   }

   swap( _vTerms.at( uiTerm ), _vTerms.back() );
   _vTerms.pop_back();
   resetIndexValues();

} // removeTerm


resetIndexValues()
// ------------------------------------------------------------------------- //
// resetIndexValues()
//
void Polynomial::resetIndexValues() {

   // now we need to test our index values and set them accordingly
   for ( unsigned int uiIndex = 0; uiIndex < (int)_vTerms.size(); uiIndex++ ) {
      _vTerms[uiIndex]._uiTermIndex = uiIndex;
   }

} // resetIndexValues


combineLikeTerms()
// ------------------------------------------------------------------------- //
// combineLikeTerms()
//
void Polynomial::combineLikeTerms() {
   
   bool bFound = false;
   for ( unsigned int uiIndex = 0; uiIndex < (int)_vTerms.size(); uiIndex++ ) {
      
      if ( uiIndex == _vTerms.size() ) {
         return;
      }         
      
      
      if ( (_vTerms.at(uiIndex)._cIndependentVariable == _vTerms.at(uiIndex+1)._cIndependentVariable) &&
          (_vTerms.at(uiIndex)._fExponent            == _vTerms.at(uiIndex+1)._fExponent) ) {
          bFound = true;   
      }

      if ( !bFound ) {
         // First two are not = then we need to increment our counter
         //uiIndex++;
      } else {         
         // We found a match add the two together
         
         if ( uiIndex != (int)(_vTerms.size()-1) ) {
            float fTotal = 0;
            char  cTemp  = _vTerms.at(uiIndex)._cIndependentVariable;
            float fExp   = _vTerms.at(uiIndex)._fExponent;
            float fTemp1 = _vTerms.at(uiIndex)._fCoefficient;
            float fTemp2 = _vTerms.at(uiIndex+1)._fCoefficient;            
   
            fTotal = fTemp1 + fTemp2;
            removeTerm( uiIndex );
            removeTerm( uiIndex + 1 );
            addNewTerm( fTotal, cTemp, fExp );
         }
      }
      // Reset our bFound
      bFound = false;
   }

} // combineLikeTerms


From looking at my code I'll try to give you a visual diagram of what is happening.
Lets say we have a polynomial with 4 terms. In main.cpp here is the order of class method calls.

poly.printPolynomial();
poly.setPolynomialByDegreeOfExponent();
poly.printPolynomial();
poly.combineLikeTerms();
poly.printPolynomial();

y = 4x^3 3x^2 5x^3 6x^2 // first print
y = 4x^3 5x^3 3x^2 6x^2 // second print after setPoly... is called

then we go into combineLikeTerms();
we start iterating from the begining of the vector
[ 0 ] [ 1 ] [ 2 ] [ 3 ] = [4x^3] [5x^3] [3x^2] [6x^2]

we have an initial condition to check if our index == our vectors size if so return.

the we have a second condition that depends on if the variable name and the exponents match if these do we have a match and we set bFound to true.

if bFound is still false we do nothing and increment our counter.

if bFound is true which in this case it is since we sorted them first and we have a pair that can be added or subtracted from each other; we check another if condition to see if our index value is not equal to our size - 1. Then we create some local variables and extract our data and store them in temp variables. We then call removeTerm() twice once for each terms' index value that we added together. Then we call addNewTerm with the values we extracted. I wrote it out on paper in the order of what was happening, because in our removeTerm function I am swapping the term index with the back term, then I am popping it from the back.

so in angle brackets it looks like this.
[0][1][2][3] uiIndex = 0; bFound = true. we call removeTerm(uiIndex) and removeTerm swaps index with back.
[3][1][2] | [0] the vertical bar represents that I popped it from the vector
[3][1][2] uiIndex still = 0, bFound still = true, second call to removeTerm(uiIndex+1) and removeTerm swaps
[3][2] | [1] then popped it from vector. Before addNewTerm is called our vector is now
[3][2] addNewTerm( values passed in )
[3][2][newTerm] we then go outside the if statement and reset bFound to false, and increment our counter. uiIndex now = 1; this is were I am stuck If i continue the .at() throws an exception. Also [3][2] should be a pair to add but their actuall indexes in the vector are [0][1][2] now, and my index is at 1. Im not sure if I need some kind of recursion or what else, I just want to be able to combine all like terms in the polynomial. Performance at this point isn't that much of an issue, just getting the algorithm to work properly is. Any kind of help will be appreciated.


Offline
 Profile  
 
 Post subject: Re: Need help with std::vector
PostPosted: Thu Aug 30, 2012 1:48 pm 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 450
I am still working on the same problem I listed above, however I am trying a different approach.
lets use a basic vector<> for simplicity. The algorithim I would need to create follows this.
vector<int> _vMember = { 1,2,3,3,3,5,5,6,9 }; This is a member variable to some class and access is in one of the classe's function with some arbitrary data in the vector. What I would like to do with this vector is simply this... for all elements that are unique I want to put them into a local vector inside the function scope. vector<int> vUnique. The other step I want to do doesn't seem intuitive at first but there are good reasons for it later. but for each of the values that are duplicates they would go into their own vector but each of these vectors are stored in a vector and this nested vector<vector<int>> is a local variable to the function. So this would be the new local temp containers.

vector<int> vUnique = { 1,2,6,9 };
vector<vector<int>> vvDuplicates = { {3,3,3}, {5,5} };

the next step of the algorithm would be to add all the 3's together then add all the 5's together

the final step would be to repopulate the member _vector and resize it accordingly..
so in the end the member vector would look like this.

_vMember = { 1,2,6,9,9,10 }; if you notice I still have 2 values of 9 but for what I am using this algorithm for the two 9s will be different, this is just an example using ints to make it a little more simple to understand what I am trying to get at.

the reason for the vector<vector<int>> is that I would be going through a double for loop and for each pass of the inner loop, I will be adding all the elements of that vector and store it to a local temp int variable (in my case a temp float variable which is extracted from a class float). This new value will be used to create a class object with this value so that this class object can be repopulated into the _vMember container. and this process will repeat for each iteration of the outer vector.

The biggest part I am struggling with is finding the duplicate values. As a note my vector has already been sorted. In my case I am using a class object that has 3 parameters. Two floats and a char
MyObject( float f1, char c, float f2 ); would be its constructor. If I have obj1 and obj2 I am not looking to see if all three elements are the same to compare them if they are (==). What I am doing is look to see if the char c and float f2 of both obj1 and obj2 are equal if they are then these two objects are consider a like. Then if they are a like the parameters f1 of both obj1 and obj2 can be added together and the parameters c and f2 stay the same. This description will make it clear why I said in the above example with ints why the two final 9's are actually different. I get it to work in some cases but in other cases it fails, when I fix it to work for the failed case, the previous working case fails. I am a bit stuck here. Any help will be apprieated.


Offline
 Profile  
 
Display posts from previous:  Sort by  
 Page 1 of 1 [ 12 posts ] 


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to:  

cron