How to give Default Argument of Std::Vector of std::pairs? - c++

I don't know how many inputs will come to my function as pair of ints. So in order to achieve that I would like to get a default parameter of std::vector of std::pair, because I want at least one pair in case there is no input. How Can I achieve this?
#include <iostream>
#include <string>
void default_function(int inp1 = 11, int inp2 = 13){ //, std::vector<std::pair<int,int>> defaultVector = XXXX
}
int main()
{
default_function();
return 0;
}
For example user can input no pairs in that case I will set them 0,0. They can input (0 , 2) as one pair, or (0 , 5), (2 , 2),(0 , 2) as three or more pairs. How to handle this?
(C++ 14 Version)

Use an initializer list as shown below
void default_function(
std::vector<std::pair<int,int>> v =
{{1,2}, {3,4}, {5,6}})
{
for(auto &p: v)
std::cout << p.first << ", " << p.second << " : ";
}
int main() {
default_function();
return 0;
}

Related

Print like a dataframe vector pairs c++

I have a map:
std::map<string , double> params{{a , 1}, {b, 6 }, {c, 7}{d,8} }
I want to print it like a python dataframe:
a b c d
1 6 7 8
Also, I dont want it to run twice.
void join_parameters(std::pair<string , double> param){
std::map<string , double> params;
params.insert(param);
for(const auto& elem : params)
{
double a, b , c,d;
if (elem.first =="a"){
a = elem.second; }
else if (elem.first =="b"){
b = elem.second;}
else if (elem.first =="c"){
c = elem.second; }
else {
d = elem.second;
}
}
std::cout << "d " << "a "<< "b " << "c "<< "\n" << d << a << b << c <<std::endl ;
}
Do you have any suggestion for me?
Your code only works for a map with 4 elements and it assumes that those elements have keys "a" till "d". If that is the case then I would suggest you to use a different data structure, for example
struct params_t {
double a,b,c,d;
};
If you do need the map then you should not make assumptions about number of elements or their keys.
You can use two strings to accumulate the two lines of output in a single loop:
#include <map>
#include <string>
#include <utility>
#include <iostream>
int main() {
std::map<std::string , int> params{{"a" , 1}, {"b", 6 }, {"c", 7},{"d",8} };
std::pair<std::string,std::string> lines;
for (const auto& e : params) {
lines.first += e.first + " ";
lines.second += std::to_string(e.second) + " ";
}
std::cout << lines.first << '\n';
std::cout << lines.second << '\n';
}
Note that I changed the mapped type to int because it looks like you want to store integers. For double you need to adjust the code to get propper formatting.

How to get the key of a map using the value in C++ STL

Get key by inputting the value of that key in C++ STL
map<int,int> m;
m[0]=8;
m[8]=7;
m[1562]=4;
m[100]=1;
auto i=m.find(1562);
cout<<endl<<i->first;
You cant. The map works by hashing the key and then using that to find the value stored in memory. It does not allow you to use the value to index the key.
What you can do is, iterate through the map to find the value and get the key from it.
int key = 0;
int value = 4;
for(auto entry : m)
{
if(entry.second == value)
{
key = entry.first;
break; // Exit from the loop.
}
}
Reference: cppreference
std::map is an ordered by key container. So to find a key by value you need to use the sequential search. For example you can use the standard algorithm std::find_if.
Here is a demonstrative program.
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
int main()
{
std::map<int,int> m =
{
{ 0, 8 }, { 8, 7 }, { 1562, 4 }, { 100, 1 }
};
int value = 4;
auto it = std::find_if( std::begin( m ), std::end( m ),
[&value]( const auto &p )
{
return p.second == value;
} );
if ( it != std::end( m ) )
{
std::cout << it->first << ' ' << it->second << '\n';
}
return 0;
}
The program output is
1562 4
Or you should use a non-standard container that allows a quick access to elements of the container by key and by value.
You may do it like this as well:
#include<iostream>
#include <map>
int findByValue(std::map<int, int> mapOfElemen, int value)
{
std::map<int, int>::iterator it = mapOfElemen.begin();
// Iterate through the map
while(it != mapOfElemen.end())
{
// Check if value of this entry matches with given value
if(it->second == value)
{
return it->first;
}
// Go to next entry in map
it++;
}
//key for the value is not found hou probably need to change this depending on your key space
return -9999;
}
int main()
{
std::map<int,int> m;
m[0]=8;
m[8]=7;
m[1562]=4;
m[100]=1;
int value = 1562;
int result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
value = 8;
result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
value = 7;
result = findByValue( m, value);
std::cout << "key for "<< value << " is " << result << std::endl;
}
The result would give this:
key for 1562 is -9999
key for 8 is 0
key for 7 is 8
key for 4 is 1562
You can use an unordered map:
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,int> m = {{0,8},{8,7},{1562,4},{100,1}};
cout<<m[1562];
return 0;
}
This will print the output as 4.

Efficient way to get key from value when map contain vector of string as value

How to get key using value which is vector of string and vice versa. Below is my code.
#include<iostream>
#include<map>
#include<string>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
std::unordered_map<std::string, std::vector<std::string>> Mymap;
Mymap["unique1"] = {"hello", "world"};
Mymap["unique2"] = {"goodbye", "goodmorning", "world"};
Mymap["unique3"] = {"sun", "mon", "tue"};
for(auto && pair : Mymap) {
for(auto && value : pair.second) {
std::cout << pair.first<<" " << value<<"\n";
if(value == "goodmorning") // how get key i.e unique2 ?
}}
}
case 1: When value is input. key is output.
Input : goodmorning
output : unique2
case 2: When key is input value is output.
Input : unique3
output: sun ,mon ,tue
Note : No boost library available.
For case 1, a combination of find_if and any_of will do the job.
For case 2, you can simply use the find method of unordered_map.
#include<iostream>
#include<map>
#include<string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
unordered_map<string, vector<string>> Mymap;
Mymap["unique1"] = { "hello", "world" };
Mymap["unique2"] = { "goodbye", "goodmorning", "world" };
Mymap["unique3"] = { "sun", "mon", "tue" };
// Case 1
string test_value = "goodmorning";
auto iter1 = find_if(Mymap.begin(), Mymap.end(),
[&test_value](const decltype(*Mymap.begin()) &pair)
{
return any_of(pair.second.begin(), pair.second.end(), [&test_value](const string& str) { return str == test_value; });
});
if (iter1 != Mymap.end())
{
cout << "Key: " << iter1->first << endl;
}
else
{
cout << "No key found for " << test_value;
}
// Case 2
test_value = "unique3";
auto iter2 = Mymap.find(test_value);
if (iter2 != Mymap.end())
{
int first = true;
for (auto v : iter2->second)
{
cout << (first ? "" : ", ") << v;
first = false;
}
cout << endl;
}
else
{
cout << "No value found for key " << test_value << endl;
}
return 0;
}
The key is stored in pair.first. Just use that if your use-case is in loop iteration as you illustrated.
If you mean in any use, without iteration, that is, given a value obtain the associated key, there is not a direct way to do that. You could build inverse maps for each value to key but that would not be really efficient considering also the fact that you would also need unique values.
Create another map going the other way for every vector entry?
If the array entries are not unique, then you would need to do the same map-to-vector, or use multimap.
Also consider using hash map (unordered_map), and stringview as ways to reduce the memory usage of the second map?
But the best answer would be the boost 2-way map, sorry. You could wrap the two maps in your own class that exposes the functionality of a 2-way map.

How sort double vector according to changes in first vector?

I would like to implement something like DoubleVector.
In this class I would also like to implement sort method, which sort v1_ and according to changes in v1_ the order in v2_ will also change.
The code is below:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class DoubleVector
{
vector<int> v1_;
vector<char> v2_;
public:
void sort()
{
//sort v1_ and also change order in v2_ according to changes in v1_
std::sort(v1_.begin(), v1_.end() /*, lambda ?*/);
}
void add(int value_v1, char value_v2)
{
v1_.push_back(value_v1);
v2_.push_back(value_v2);
}
void print()
{
const auto size = v1_.size();
for (size_t i=0;i<size;++i)
{
cout << v1_[i] << " " << v2_[i] << endl;
}
}
};
int main()
{
DoubleVector dv;
dv.add(6, 'g');
dv.add(2, 'r');
dv.add(3, 'y');
dv.add(4, 'a');
cout << "Before sort:" << endl;
dv.print();
dv.sort();
cout << "After sort:" << endl;
dv.print();//the values in v2_ are in the same order they don't change order according to v1_ changes
return 0;
}
As you can see DoubleVector before sort contains:
6 g
2 r
3 y
4 a
And after sort contains:
2 g
3 r
4 y
6 a
I would like to get:
2 r
3 y
4 a
6 g
So the first vector v1_ has been sorted, but the second still has got the same order and I would like to change order of elements in second v2_ vector according to changes in v1_.
I can write it, but I would like to do it in a fast and clean way, maybe using lambda as third argument in std::sort function? Vectors v1_ and v2_ in class DoubleVector must stay as they are.
Thank you very much.
Make a vector of std::pair<int,char> instead. Since operator < on the pair compares first and decides ties on the second, sorting std::vector<std::pair<int,char>> will produce the exact effect that you want:
vector<pair<int,char>> v;
v.push_back(make_pair(6, 'g'));
v.push_back(make_pair(2, 'r'));
v.push_back(make_pair(3, 'y'));
v.push_back(make_pair(4, 'a'));
sort(v.begin(), v.end());
for (int i = 0 ; i != v.size() ; i++) {
cout << v[i].first << " " << v[i].second << endl;
}
Demo.
You can do something like this:-
vector< pair<int,char> >v;
//do what you want
sort(v.begin(),v.end())
The sort function by default sorts according to first value but you can always define according to which criteria should the sort work
C++ STL - How does the third argument of the STL sort() work?
Try the following.
The way it works is to sort the position key pair based on the int vector value only and then use this ordering to extract values.
#include <iostream>
#include <algorithm>
#include <vector>
class dv
{
std::vector<int> _v1;
std::vector<char> _v2;
std::vector<std::pair<int, int> > _order;
public:
inline bool operator() (const std::pair<int, int>& v1_index_1,
const std::pair<int, int>& v1_index_2) const {
return _v1[v1_index_1.first] < _v1[v1_index_2.first];
}
void sort() {
std::sort(_order.begin(), _order.end(), *this);
}
void add(int value_v1, char value_v2) {
_order.push_back(std::pair<int, int>(_v1.size(), _v2.size()));
_v1.push_back(value_v1);
_v2.push_back(value_v2);
}
void print() {
const auto size(_v1.size());
for (size_t i=0; i<size; ++i) {
std::cout << _v1[_order[i].first]
<< " "
<< _v2[_order[i].second]
<< std::endl;
}
}
};
int main() {
dv dv;
dv.add(6, 'g');
dv.add(2, 'r');
dv.add(3, 'y');
dv.add(4, 'a');
std::cout << "before sort: " << std::endl;
dv.print();
std::cout << "sorting: " << std::endl;
dv.sort();
std::cout << "after sort: " << std::endl;
dv.print();
return 0;
}

more modern way of looping through C++ arrays

Recently I have found a lot of examples, most of them regards the C++ 98, anyways I have created my simple-array and a loop (codepad):
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
Output:
value of a: Apple
value of a: Banana
value of a: Orange
Segmentation fault
It's working fine, except the segmentation fault at the end.
My question is, does this array/loop through is done a good way? I am using C++ 11 so would like to be sure it fits the standards and couldnt be done a better way?
In C/C++ sizeof. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
as others have pointed out, std::array is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof is failing the way it is, so I still think this is the better answer.
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Nope. Totally a wrong way of iterating through an array. sizeof(texts) is not equal to the number of elements in the array!
The modern, C++11 ways would be to:
use std::array if you want an array whose size is known at compile-time; or
use std::vector if its size depends on runtime
Then use range-for when iterating.
#include <iostream>
#include <array>
int main() {
std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
// ^ An array of 3 elements with the type std::string
for(const auto& text : texts) { // Range-for!
std::cout << text << std::endl;
}
}
Live example
You may ask, how is std::array better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end on it.
sizeof tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:
#include <array>
#include <string>
#include <iostream>
int main()
{
std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
for (auto& text : texts) {
std::cout << text << '\n';
}
return 0;
}
ideone demo: http://ideone.com/6xmSrn
you need to understand difference between std::array::size and sizeof() operator. if you want loop to array elements in conventional way then you could use std::array::size. this will return number of elements in array but if you keen to use C++11 then prefer below code
for(const string &text : texts)
cout << "value of text: " << text << endl;
If you have a very short list of elements you would like to handle, you could use the std::initializer_list introduced in C++11 together with auto:
#include <iostream>
int main(int, char*[])
{
for(const auto& ext : { ".slice", ".socket", ".service", ".target" })
std::cout << "Handling *" << ext << " systemd files" << std::endl;
return 0;
}
How about:
#include <iostream>
#include <array>
#include <algorithm>
int main ()
{
std::array<std::string, 3> text = {"Apple", "Banana", "Orange"};
std::for_each(text.begin(), text.end(), [](std::string &string){ std::cout << string << "\n"; });
return 0;
}
Compiles and works with C++ 11 and has no 'raw' looping :)
sizeof(texts) on my system evaluated to 96: the number of bytes required for the array and its string instances.
As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0]) would give the value of 3 you were expecting.
Add a stopping value to the array:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange", ""};
for( unsigned int a = 0; texts[a].length(); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
In my point of view:
It is because the sizeof() operator returns the size
of a type in bytes.
So, Simply we can use size() instead of sizeof(). If
we need or must use sizeof() we have to divide it
with sizeof(dataType):
First way:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange"};
for(int a = 0; a < size(texts); a++){
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
Second way:
#include <iostream>
using namespace std;
int main ()
{
string texts[] = {"Apple", "Banana", "Orange"};
for(int a=0; a<sizeof(texts)/sizeof(string); a++)
{
cout << "value of a: " << texts[a] << endl;
}
return 0;
}
Feels like illegal but this works:
So basically it is dynamic multidimensional array iteration termination case and it differs a bit from one dimensional solution, last element is -1 and it is stop value for cycle (I am new to C++ but this method me likes)
int arr[][3] = {{164, 0, 0}, {124, 0, 0}, {92, 4, 0}, {68, 4, 0}, -1};
for(int i = 0; arr[i][0]!=-1; i++)
{
cout << i << "\n";
}
You can do it as follow:
#include < iostream >
using namespace std;
int main () {
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts) / 32; a++ ) { // 32 is the size of string data type
cout << "value of a: " << texts[a] << endl;
}
return 0;
}