I'm attempting to remove an item from an XSLT 3 map, but I keep running into what to do with the output of the map:remove function. At this point, I'm using a throwaway variable to make sure I don't return anything on the output.
<xsl:if test="map:size($aMap) > 0">
<xsl:variable name="throwaway" select="map:remove($aMap, map:keys($aMap)[1])"/>
</xsl:if>
Is there an easier way to do this?
Maps are immutable so while you can call map:remove($aMap, map:keys($aMap)[1]) without storing the result of that call it doesn't change the map the variable aMap is bound to, you need to store the result of the remove call, in a new variable, or rebind the existing variable; so
<xsl:variable name="aMap" select="map { 'a' : 1, 'b' : 2, 'c' : 3 }"/>
<xsl:message select="map:remove($aMap, 'b')"/>
<size>{map:size($aMap)}</size>
<xsl:variable name="aMap" select="map:remove($aMap, 'b')"/>
<size>{map:size($aMap)}</size>
gives
<size>3</size>
<size>2</size>
Related
I have a function called OperatorSorter and I basically want to sort a special character list.
ex:
['-', '*', '/', '+', '^'] => ['^', '*', '/', '-', '+']
What I want to do is make a Calculator and it will make an operator list. But it has to order operations and it should sort them.
But I can't use their ascii's due to they are not in order this way.
May someone give me a good sort way to sort this in c++?
What you need is a mapping of sorts. For example consider the following, using std::map:
std::map<char, int> sortWeigths { {'^', 0} , {'*', 1} , {'/', 1} , {'-', 2} , {'+', 2} };
Where some operators have the same weights.
Then you can use a custom comparator like this:
bool CompareOperators(char a, char b)
{
return sortWeigths[a] < sortWeigths[b];
}
That's just the rough outline and I hope you get the idea.
Note that when using std::sort identical elements might switch positions. E.G. input
['-', '*', '/'] might end up as either ['*', '/', '-'] or [ '/', '*', '-']. If that's important consider std::stable_sort.
Assuming you only sort these characters. If you map (translate) the first character to, say 'a', the next in your preferred order to 'b', next to 'c' etc. then you can use a regular sort. After the sorting is done you map the characters back.
If two of your characters have equal value you need to handle those cases separately.
Or you can create a map assigning keys to each symbol. This way you can add new symbols if required. Following key-value pairs are already sorted w.r.t the key.
#include <map>
std::map<int,char> symbol_map = {{1,'^',}, {2,'*'}, {3,'/'}, {4,'-'}, {5,'+'}};
std::multimap<int,char> symbol_map2 = {{1,'^',}, {2,'*'}, {2,'/'}, {3,'-'}, {3,'+'}};
So I have been brushing up a bit on c++ and found out I am very rusty in comparison to my other languages. I have been working on this problem from codewars.com
Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].
To accomplish this task I wanted to create a multidimentional vector to hold unique values of the provided list in the first dimension and corresponding number of occurences in the second dimension. However, I was unfamiliar with c++'s syntax to accomplish this, so I just made 2 separate vectors.(instances, countOfInstance)
Essentially what my algorithm will do is:
loop through the provided array(arr)
check to see if the value in "arr" does not exists in "instances"
If not found then push the value in "arr" to "instances",
add a counting value of 1 that corresponds to this index in "countOfInstance"
and then add the value in "arr" to the nFilteredVector.
If the value in "arr" is found in "instances" then:
Find the index value of "arr" in "instances"
Use this index to find its corresponding count value in "countOfInstances"
Determine if the count is less than the provided "N"
if less than "N" add to "nFilteredVector"
Then increment the value in "countOfInstances"
However, when I try to access the index of "CountOfInstances" with index of "instances" i get an odd error
no viable overloaded operator[] for type 'std::vector'
if (countOfInstances[std::find(instances.begin(), instances.end(),arr[i])] <=2){
Correct me if I am wrong, but it is my understanding that the find function returns the index value of the found element. I was wanting to use that index value to access "countOfInstances" vector.
Can someone please help me figure out the correct syntax of what I am looking for. Bonus points for integrating "instances" and "countOfInstance" as a multidimentional vector!!
#include <algorithm>
std::vector<int> deleteNth(std::vector<int> arr, int n)
{
std::vector<int> nFilteredVector;
std::vector<int> instances;
std::vector<int> countOfInstances;
for (int i =0; i < arr.size();i++){
if(std::find(instances.begin(), instances.end(),arr[i])==instances.end()){//value not found need to add corresponding value to instances vector then add an element of 1 to the correpeonding index of the countOfInstance vector.
instances.push_back(arr[i]);
countOfInstances.push_back(1);
nFilteredVector.push_back(arr[i]);
}else{ // value is found just need to increment the value in countOfInstances
//find the instance of the value in arr in the instance vector, use that value to find the corresponding value in countOfInstance
if (countOfInstances[std::find(instances.begin(), instances.end(),arr[i])] <=n){
nFilteredVector.push_back(arr[i]);
}
countOfInstances[std::find(instances.begin(), instances.end(),arr[i])]++;
}
return nFilteredVector;
}
Here are some examples of what codewars will be testing for
{
Assert::That(deleteNth({20,37,20,21}, 1), Equals(std::vector<int>({20, 37, 21})));
Assert::That(deleteNth({1,1,3,3,7,2,2,2,2}, 3), Equals(std::vector<int>({1, 1, 3, 3, 7, 2, 2, 2})));
}
If what you are trying to achieve is get the index of the found item in a std::vector, the following does this job using std::distance:
#include <algorithm>
#include <vector>
auto iter = std::find(instances.begin(), instances.end(),arr[i]);
if ( iter != instances.end())
{
// get the index of the found item
auto index = std::distance(instances.begin(), iter);
//...
}
I believe std::find return an iterator on instances. You cannot use an iterator from one list on another and you cannot use an iterator as an index.
What you could do is use
std::find(instances.begin(), instances.end(), arr[i]) - instances.begin()
as your index. This is a bit ugly, so you might also want to look a bit more at iterators and how to use them.
I have been trying to create an unordered map that takes in (x, y) values as the key to look for its corresponding value.
For example) x=-1 y=0 I would get a certain symbol '$'
I have created the following unordered map:
static boost::unordered_map<pair<char, char>, char> map;
But I am having problems when I try to insert values into the map doing the following:
map.insert({ { '-1', '0' }, '$' });
It doesn't seem like I am getting a correct map.
Whenever I do the following within the lookup of the map I get this:
char temp = map[{'-1','0'}];
temp = '0'
Any help will be much appreciated,
Thank you,
Al
'-1' is a multi-character constant, with a value that's probably out of range for char. If you mean to use the values -1 and 0, then remove the quotes.
For portability, if the values might be negative, you should use a type that's guaranteed to be signed (like int or signed char). Otherwise, you might get a surprise if you change to a compiler that gives an unsigned char.
Based on the boost documentation here:
http://www.boost.org/doc/libs/1_41_0/doc/html/boost_propertytree/container.html
"There may be multiple children with the same key value in a node. However, these children are not necessarily sequential. The iterator returned by find may refer to any of these, and there are no guarantees about the relative position of the other equally named children."
Sample XML:
<library>
<book><title>Title_1</title></book>
<book><title>Title_2</title></book>
<book><title>Title_3</title></book>
</library>
Sample boost code:
ptree pt;
pt.push_back(ptree::value_type("book", ptree("title")))
// This finds the first book and cannot iterate to the second one:
ptree::const_iterator it = pt.find("book");
So knowing that, how would you get all the books and be sure you go them all?
You have to use the equal_range function:
std::pair < ptree::const_assoc_iterator, ptree::const_assoc_iterator> bounds =
pt.equal_range("book");
for (ptree::const_assoc_iterator it = bounds.first; it != bounds.second ; ++it)
{
// process *it
}
I'm trying to write some c++ classes for interfacing with LUA and I am confused about the following:
In the following example: Wherigo.ZCommand returns a "Command" objects, also zcharacterFisherman.Commands is an array of Command objects:
With the following LUA code, I understand it and it works by properly (luaL_getn returns 3 in the zcharacterFisherman.Commands c++ set newindex function):
zcharacterFisherman.Commands = {
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
But when the array is defined with the following LUA code with a slightly different syntax luaL_getn returns 0.
zcharacterFisherman.Commands = {
Talk = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk2 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
Talk3 = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
All objects are defined in c++ and the c++ objects hold all the object members so I am trying to just connect LUA to those c++ objects. Is this enough or do I need to post some of my code??
Lua is correct.
Your first example is forming a table that contains exactly three entries with indices 1, 2, and 3, none of which are specified explicitly. In this case table.maxn(), the # operator, and lua_objlen() all agree that there are three array elements.
Your second example is forming a table that contains exactly three entries with indices "Talk", "Talk2", and "Talk3", all specified explicitly but none are integers. In this case, table.maxn(), the # operator, and lua_objlen() all agree that there are zero array elements.
Why is this the right answer?
A Lua table is an associative array that can map values of any type (except nil) to values of any type (again, except nil). There is no other general container type in Lua, so tables are used for essentially everything. The implementation is not part of the Lua specification, but in practice a table is indexed as a hash table, and there is no natural ordering of the keys.
However, a common use case for tables is as a container that acts like a conventional array. Such a container has contiguous integer indices, and can be iterated in order. The table implementation makes this particularly efficient for integer keys starting at 1. These entries in the table are physically allocated as a contiguous array, and the keys are neither hashed nor stored. This saves storage space both in allocation overhead and by not storing some of the keys at all. It also saves run time since access is by direct calculation rather than by computing a hash and verifying the matching value.
Since arrays are just tables, the table initializer syntax has been designed to make that case easy and clear, as well as to support the other common use case where keys are strings that happen to be valid identifiers.
Lua 5.1 vs. Lua 5.0
In the current release of Lua (5.1.4, but this is true of all 5.1 releases) the Lua 5.0 functions table.getn(), table.setn(), luaL_getn(), and luaL_setn() are all deprecated, as is the common usage of a table field n for an array to indicate its array length. The table.getn() function is replaced by the # operator, and luaL_getn() by lua_objlen(). There is no equivalent to the setn() functions since Lua now manages the array size behind the scenes.
The # operator is defined on a table to return an integer such that indexing the table by the next larger integer returns nil. For an empty array (e.g. a = {}), it returns 0 because a[1] == nil. For a normal array, it returns the largest index in use. However, if an array has holes (missing elements) then it can return the index preceding any hole or the last index in use. If the actual largest integer index in use is required, the new function table.maxn() can be used, but it has to iterate over all table entries to find that maximum value and thus should only be used when using # can't.
This leads to a now common idiom for adding elements to an array: a[#a+1] = "some new value". This idiom is now often recommended in place of table.insert() for extending tables.
luaL_getn is for getting the highest numeric element of an array in Lua. An array is a table with only integer indices. When you define a table in Lua (the first example) without explicitly setting indices, you will get an array with elements 1, 2, and 3. Naturally, luaL_getn returns a 3 here. luaL_getn is NOT defined to return the number of elements in the table, it is defined to return the highest numeric index in the table (see http://www.lua.org/manual/5.1/manual.html#pdf-table.maxn)
The second example is NOT using numeric indices, and this table is not a Lua array -- it is more like a hash table. Since luaL_getn only works on true arrays, you wouldn't expect it to work here.
Unfortunately, there is no simple way to get the number of elements in a table (lua_objlen solves a related problem, but does not fix this one). The only way to do it is to either:
Always use array notation. Don't ever use anything else as the keys in your table. You will get a lot of speed-ups this way.
Iterate through your table and count the number of elements when you wish to know the table's size. The language does not provide a one-line method for getting the size of a full table, since general tables are implemented using hashes and do not track their element count.
Lua tables combine both hashtables and standard arrays.
Your first example is equivalent to:
zcharacterFisherman.Commands = {
[1] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
[2] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
[3] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
getn helps you to find an empty numeric entry. If t[1]==nil then it is likely that table.getn(t) == 0. In your second example, you do not assign zcharacterFisherman.Commands[1], which is why you are getting 0.
zcharacterFisherman.Commands = {
[1] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
[2] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
[3] = Wherigo.ZCommand{a="Talk", b=false, d=true, c="Nothing available"},
}
zcharacterFisherman.Commands[1]=nil
print(table.getn(zcharacterFisherman.Commands))
This code will print 0 (or possibly a number >=3)
In general, there is no way to directly get the number of elements in the hashtable portion of the table without iterating over them (e.g. with pairs() )