In my output:
test-a , test-b
test-a , test-cIt seems ok but I want my output:
0 , 1
0 , 2e.g if test-a is 0, test-b is 1, test-c is 2, test-d is 3 etc etc
If we assume that you want an ascending numeric value
to represent each unique string in ascending sorted
order, one possible approach is to use a map which
will eliminate duplicates and automatically sort
the elements.
Consider the following example.
(1) A map consisting of pairs of strings and ints
is created.
(2) Each source and destination string is added to
the map, which will discard duplicates. As an initial
value the int in each pair is set to 0.
(3) After all strings have been added to the map,
each element in the map is now given a unique
numeric value. With the sample data the map will
have three pairs in it:
test-a,0
test-b,1
test-c,2
(4) To overcome the vector overrun problem mentioned
by Barry, a dummy object is added to the end of the
vector and the loop is altered to use arr.size()-1.
I leave it as an exercise for you to ensure that
this approach will produce valid results for all
encountered strings in the actual XML file.
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include "tinyxml2.cpp"
using namespace std;
using namespace tinyxml2;
class SrourceDistinationClass
{
public:
string source;
string distination;
};
int main()
{
// Read the sample.xml file
XMLDocument doc;
doc.LoadFile("Files/test.xml");
vector<SrourceDistinationClass> arr;
map<string, int> mapstrs;
const XMLElement *element = doc.FirstChildElement("SwanDemandList");
for (const XMLElement *child = element->FirstChildElement("SwanDemand"); child != 0; child = child->NextSiblingElement())
{
SrourceDistinationClass srcDistObject;
srcDistObject.source = child->Attribute("SourceRouter");
srcDistObject.distination = child->Attribute("DestinationRouter");
arr.push_back(srcDistObject);
// create elements in the map for each unique string
mapstrs.insert(pair<string, int>(srcDistObject.source, 0));
mapstrs.insert(pair<string, int>(srcDistObject.distination, 0));
}
// allocate a unique number to each string in the map
int idx = 0;
map<string, int>::iterator mi;
for (mi = mapstrs.begin(); mi != mapstrs.end(); ++mi)
{
mi->second = idx++;
}
// add a dummy object at end of vector
SrourceDistinationClass srcDistObject;
srcDistObject.source = "";
srcDistObject.distination = "";
arr.push_back(srcDistObject);
//for (int i = 0; i < arr.size(); i++)
for (int i = 0; i < arr.size()-1; i++)
{
if (arr[i].source != arr[i + 1].source || arr[i].distination != arr[i + 1].distination)
{
std::cout << arr[i].source << " , " << arr[i].distination << endl;
std::cout << mapstrs[arr[i].source] << " , " << mapstrs[arr[i].distination] << endl;
}
}
return 0;
}
Output:
test-a , test-b
0 , 1
test-a , test-c
0 , 2
E&OE
- Wayne