Aug 12, 2014 at 5:20am UTC
My definition is
---------------------------------
using namespace std;
struct goodl { int line; string trl; };
struct vetor { goodl gline };
vector<vetor> goodlines;
-----------------------------------
I am not experienced with this topc and need help
I will use goodlines to store found lines in a text file
in the int I will store the line number form the file
I need to do two things that I don't how to
1) adding and reading data to from the vector
2) I need to sort the data in my vectior in
increasing line numbers (they can be mixed up)
Please advice
Aug 12, 2014 at 7:59am UTC
Why the vetor? It doesn't seem to add anything. You could as well have vector<goodl>.
See the std::sort. It has two versions. The first uses operator< of the elements. The second uses whatever binary predicate you give it.
Actually, you could replace the goodl with std::pair<int ,string>
. That already has operator<.
Aug 12, 2014 at 11:22am UTC
Ohh, if it is declared as the pair you suggest then how to adress the items, if they are nameless?
Last edited on Aug 12, 2014 at 11:31am UTC
Aug 13, 2014 at 5:26am UTC
Ohh I get a lot of compilation errors!
Should not the operator be specified with gline in stead of goodl?
Or am I lost?
Aug 13, 2014 at 5:34am UTC
I finally got through the compilator with code structure
------------------------
pair <int, string> gdata;
vector<pair<int, string> > goodlines;
------------------------
To fetch data I used
---------------------
trl = goodlines[goodline].second;
------------------------
To sort i could simply write
...............................
sort(goodlines.begin(), goodlines.end());
And to push_back data
--------------------------
gdata.first = infLno; // a number
gdata.second = trline; // a string
goodlines.push_back(gdata);
Last edited on Aug 13, 2014 at 6:59am UTC
Aug 13, 2014 at 6:58am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
int main ()
{
// If we can assume that no linenumber is negative, then unsigned
std::vector<std::pair<unsigned int ,std::string>> myvector;
myvector.reserve(10); // guess for final size; less reallocations
// C++11 streamlined push_backs, could be in file-reading loop
myvector.emplace_back( 3, "Hello" );
myvector.emplace_back( 4, "world" );
myvector.emplace_back( 1, "Dolly:" );
myvector.emplace_back( 4, "again" );
for (auto & x: myvector)
std::cout << ' ' << x.first << ' ' << x.second;
std::cout << '\n' ;
std::sort( begin(myvector), end(myvector) );
for (auto & x: myvector)
std::cout << ' ' << x.first << ' ' << x.second;
std::cout << '\n' ;
return 0;
}
Last edited on Aug 13, 2014 at 7:00am UTC