Im having this issue with comparing pairs. I want use find() to my vector which contains pairs like this:
vector<pair<PersonID, Cost>> friendlist;
PersonID and Cost are both just regular ints. And the problem here is that I want to specifically use the find() just on the PersonID, I'm not interested on the Cost.
if(friendlist.begin(), friendlist.end(), std::make_pair(toid, Cost)) !=
friendlist.end() )
toid here is the id I want to look for within the vector. So what I should do with the other field that make_pair requires?
std::find_if(friendlist.begin(), friendlist.end(),
[=](const std::pair<PersonID, Cost>& elem) {
return elem.first == toid;
});
Related
I'm looking for a simplest way to sort list based on given value instead of using two list.
Example I have list [a,b,c,d], with a given value d,I can sort it like this:
But if I have an object list, how can I sort it based on given value?
Example
List<ABC> list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
I have value 3. I want to sort the list become
List<ABC> list = [{fid:3,name:"c"},{fid:1,name:"A"},{fid:2,name:"b"},{fid:4,name:"d"},{fid:4,name:"d"}]
You just need to perform custom sorting here, rest of the things will remain same.
List list = [{"fid":1,"name":"z"},{"fid":10,"name":"b"},{"fid":5,"name":"c"},{"fid":4,"name":"d"}];
list.sort((a,b)=> a["fid"].compareTo(b["fid"]));
int fidIndex=4;
int indexToRemove=list.indexWhere((element) => element["fid"]==fidIndex);
Map<String,dynamic> removedItem= list.removeAt(indexToRemove);
list.insert(0,removedItem);
print(list);
You can sort list using comparator:
const list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
const fixedFid = 3
const sortedList = list.sort( (item1, item2) => {
if (item1.fid === fixedFid){
return -1
}
if (item2.fid == fixedFid){
return 1
}
return item1.fid.localeCompare(item2.fid)
})
As stated in the title, I'm trying to find the index of an element in a vector of pairs. I have the following vector: std::vector<std::pair<std::string, double>> dict.
The content of my dict is:
Name1 11
Name2 9
Name3 10
Name4 12
Name5 13
All I have in order to find the index is the first attribute of the pair. For example I have Name5 and I would like to find 4. (Since Name5 is the fifth element).
Does anyone have an idea how to do it ?
I tried something but it doesn't seem to work:
auto it = std::find(dict.begin(), dict.end(), movieName);
where movieName is an std::string with "Name5" inside.
Thank you!
You can use a predicate to decide which entries in the vector should match. It's easiest to do that with a lambda:
auto it = std::find_if(dict.begin(), dict.end(),
[&](const auto& pair) { return pair.first == movieName; });
After you have the iterator, compare it to dict.end() to see if there was any match, and if there's a match you can convert it to an index into the vector using std::distance(), as d4rk4ng31 commented under the question.
I would simply go with a normal for_each loop.
So:
int index = 0;
for(const auto& pair : dict) {
if(pair.first == <whatever>) {
break;
}
index++;
}
//if index == dict.size() then print element not found
Other way would be using std::find_if() ( Thanks #Tony Delroy :) )
auto index = std::distance(dict.begin(), std::find_if(dict.begin(), dict.end(), [&](const auto& pair) { return pair.first == movieName; }));
I have an app that is reading an ingredients list. At this point I've already retrieved a list of the 2500 most common ingredients. So I've got a list of, say 10 ingredients as strings, and a list of 2500 ingredients, with names as well as other properties. If an ingredient in this list of strings matches the name of an ingredient in the list of ingredients, I'd like to add it to another list third list, of ingredients that exist. The only way I know how to do that is with basically a for loop.
I'd do it as
fun compareLists(listOfIng: List<String>): List<ListIngredientsQuery.Item> {
var returnList = mutableListOf<ListIngredientsQuery.Item>()
for (ing in listOfIng) {
for (serverIngredient in MyApp.metaIngredientList!!) {
if (serverIngredient.name() == ing) {
returnList!!.add(serverIngredient)
}
}
}
return returnList
}
Which would technically work, but I have to imagine there's a better, faster way than iterating over 2500 items, as many times as there are Ingredients in an Ingredient list. What is the like, proper, preferred by real developers, way of doing this.
As each ingredient name is unique, you can use hash map for storing your 2500 ingredients with its name as the key. This way you do not need to loop over that huge collection any more, but just look thing up by the name and let the hash map deal with it.
To put some code to what Marcin said, here is what I would do:
fun compareLists(listOfIng: List<String>) =
MyApp.metaIngredientList!!
.associateBy { it.name() }
.let { metaIngredientMap -> listOfIng.mapNotNull { metaIngredientMap[it] }}
Or if we wanna avoid using !!
fun compareLists(listOfIng: List<String) =
MyApp.metaIngredientList
?.associateBy { it.name() }
?.let { metaIngredientMap -> listOfIng.mapNotNull { metaIngredientMap[it] }}
?: emptyList<ListIngredientQuery.Item>()
Of course, ideally, you would want that MyApp.metaIngredientList to be already a Map and not convert it into a Map for each operation
This question already has answers here:
How to filter a Java Collection (based on predicate)?
(29 answers)
Closed 6 years ago.
I want to search in a List and my List is look like
List<Employee> oneEmp= new ArrayList<Employee>();
List<Employee> twoEmp= new ArrayList<Employee>();
oneEmp= [Employee [eid=1001, eName=Sam Smith, eAddress=Bangluru, eSalary=10000000], Employee [eid=0, eName=, eAddress=, eSalary=null], Employee [eid=1003, eName=Amt Lime, eAddress=G Bhagyoday, eSalary=200000], Employee [eid=1004, eName=Ash Wake, eAddress=BMC, eSalary=200000], Employee [eid=1005, eName=Will Smith, eAddress= Delhi, eSalary=200000], Employee [eid=1006, eName=Shya Ymwar, eAddress=Madras, eSalary=50000], Employee [eid=1007, eName=Nag Gam, eAddress=Pune, eSalary=10000000], Employee [eid=1008, eName=Arti, eAddress=Delhi, eSalary=10000000]]
twoEmp= [Employee [eid=0, eName=null, eAddress=null, eSalary=100000], Employee [eid=0, eName=null, eAddress=null, eSalary=50000], Employee [eid=0, eName=null, eAddress=null, eSalary=200000]]
I am using code like this:-
for(Employee two : twoEmp){
for (Iterator<Employee> iterator = oneEmp.iterator(); iterator.hasNext(); ) {
Employee e = iterator.next();
if (e.geteSalary() != null && two.geteSalary() != null && e.geteSalary().compareTo(two.geteSalary()) == 0) {
finalEmpList.add(e);
}
}
}
But this still required 2 for loop
I am using JAVA 1.6
My Employee class has attributes:
//Employee class
int eid;
BigInteger eSalary;
String eName, eAddress;
Now I want to get all the objects in List who's Salary = 10000000
result should be :
[Employee [eid=1001, eName=Sam Smith, eAddress=Bangluru, eSalary=10000000], Employee [eid=1007, eName=Nag Gam, eAddress=Pune, eSalary=10000000], Employee [eid=1008, eName=Arti, eAddress=Delhi, eSalary=10000000],.........................]
I would like to achieve this without using any loop or minimum loop required because data will be large
Yes, it is possible to avoid the loop using streams.
First, consider using a generic collection:
List<Employee> employees = new ArrayList<>():
//add all employees to the list
Now you can use streams to filter your list
List<Employee> filtered = employees.stream()
.filter(emp -> emp.getSalary() == 10000000)
.collect(Collectors.toList());
Edit: Probably Stream library is still using some kind of loop internally but while its implementation is hidden from me I do not worry.
A List is a sequential container, to do any kind of filtering on a list, your only option is to iterate over it.
For the query you mentioned,you can use the Map data structure with a BigInteger type for the key (representing the salary) and a List<Employee> for the mapped value type. This will enable you to look for all the employees that earn a certain salary in constant time without having to iterate over the whole list.
Unfortunately though, this solution can't help you do any other queries like "how many employees earn more than 60000", to preform all types of queries on a large data set you should use a database.
PS: You don't need to use the BigInteger type for the salary, unless you think someone earns more than 2,147,483,647
Something like this should do the trick; iterate over the List, and remove the items which you don't want, leaving only the ones which you do want.
List myList = new ArrayList(); //... add items
[...]
for (Iterator<Employee> iterator = myList.iterator(); iterator.hasNext(); ) {
Employee e = iterator.next();
if (e.getSalary() != 10000000) {
iterator.remove();
}
}
//your list now contains only employees whose salary = 10000000
Edit: And no, you cannot do this without a loop. In order to do this kind of thing, you have to iterate over your Collection using a loop. Even if you use a library or the Java Streams API to do this, it will still use a loop of some sort under the hood. However, this will be quite efficient, even with as large dataset. (How large ? Why do you want to avoid using a loop ?)
I'm using PicoJSON to handle JSON that I get from JavaScript into C++.
If I have a JSON with keys and values of the form {"val1":3, "val2":4} I can get the value of every specific key like so:
picojson::value v;
const string json2("{\"val1\":3,\"val2\":4}");
int val1 = (int)v.get("val1").get<double>(); // val1 will be equal to 3
int val2 = (int)v.get("val2").get<double>(); // val2 will be equal to 4
The problem is that I have an array of objects coming from JavaScript in the form of JSON that look like [{"name": 3},{"name": 1},{"name": 2}]. So now the code will look like this:
picojson::value v;
const string json1("[{\"name\": 3},{\"name\": 1},{\"name\": 2}]");
I am expected to sort them so the expected output should be:
"[{\"name\": 1},{\"name\": 2},{\"name\": 3}]"
Do I have to use a 'for loop' with a linked list to somehow extract that data to sort it? If so, how?
Maybe this can be extracted using regular expressions? If so, how?
Should the array can be converted into array of arrays in order to sort it? If so, how?
Do I have to build a struct or a vector to get a sortable data structure recognisable by
C++? If so, how?
Note: The number of elements varies - it can be greater/smaller.
EDIT:
Can this task be solved if the data structure is in this form (just like I had with {"val1":3, "val2":4} ) :
{"name3": 3, "name1" : 1, "name2": 2, "name97" : 97, ... }
I am flexible to changing it so that C++ would be able to handle it.
Would it then be possible to traverse every key and sort in by value ? If yes, how to do it?
You can put your data into a vector and sort it.
array arr = v.get<array>();
vector<int> vi;
for (array::const_iterator it = arr.begin(); it != arr.end(); ++it) {
vi.push_back((int)(*it).get("name").get<double>());
}
sort(vi.begin(), vi.end());
stringstream ss;
vector<int>::const_iterator it;
for (ss<<"[", it = vi.begin(); (it+1) != vi.end(); ++it) {
ss<<"{\"name\": "<<(*it)<<"},";
}
ss<<"{\"name\": "<<(*it)<<"}]";
cout<<"Output: "<<ss.str()<<endl;
Here is outputs:
Input: [{"name": 3},{"name": 1},{"name": 2}]
Output: [{"name": 1},{"name": 2},{"name": 3}]