How to set values in C++ template object? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create a template class that will allow me to print the contents of an object, however, being new to this, I am struggling to set the values of the data.
If, for example, I have a template that takes two typename parameters, how would I go about setting the values? Must I treat every instance of a template in a similar manner to an array or vector?
Pair<int, double> first, second;
Obviously first = 10 does not work. What am I doing wrong?

You create two Pair objects, so you cannot assign 5 to one of them, since 5 is not a Pair.
Pair<int, double> first, second; // means that you have TWO pairs!
// it was equal to:
// Pair<int, double> first;
// Pair<int, double> second;
first.first = 5;
first.second = 3.14f;
second.first = 3;
second.second = 7.421f;
You probably wanted something like this:
Pair<int, double> myPair; // only 1 pair
myPair.first = 5;
myPair.second = 3.14f;

Hopefully you are using std::pair and not writing your own pair class.
other than what has already been answered to you, you must also be familliar with std::make_pair which creates a pair and deducts the types from the arguments, thus making your code smaller and more readable.
example:
auto myPair = std::make_pair(4,5.6);

Related

Using a vector of unsigned chars in a map [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need help using unsigned chars in std::vectors that are inside of a std::map.
This is how I declare the std::map:
std::map<int, std::vector<unsigned char>> DataMap;
The problem comes when I try to assign a std::vector to the std::map.
it->first comes from another std::map, as this code is inside a loop.
std::vector<unsigned char> charHolder;
for(int i = 0; i < 10; i++)
{
charHolder.push_back('2');
}
DataMap.insert(std::pair<int, std::vector<unsigned char>(it->first, charHolder));
The errors:
Template argument 2 is invalid
I need to assigned a char[] array to the 2 place in the std::map. I've tried an array, but I had no luck.
You are missing a > character
DataMap.insert (std::pair<int, std::vector<unsigned char>>(it->first, charHolder));
^
You may use uniform initializer as following:
DataMap.insert ({it->first, charHolder});
Some of the many fun and varied ways to get data into a map:
std::map<int, std::vector<unsigned char>> DataMap;
void add(int i, std::vector<unsigned char> v)
{
// efficient move versions
DataMap.emplace(i, std::move(v));
DataMap[i] = std::move(v);
DataMap.insert(std::make_pair(i, std::move(v)));
DataMap.emplace(std::piecewise_construct,
std::make_tuple(i),
std::forward_as_tuple(std::move(v)));
// less efficient copy versions
DataMap.emplace(i, v);
DataMap[i] = v;
DataMap.insert(std::make_pair(i, v));
DataMap.emplace(std::piecewise_construct,
std::make_tuple(i),
std::make_tuple(v));
}

Extract vector from std::map<int, std::vector> [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Here is my code
#include <iostream>
#include <map>
#include <string>
#include <vector>
typedef std::vector<int> VectorInt;
typedef std::map<int, VectorInt> MapVectorInt;
int main() {
MapVectorInt myMap;
VectorInt v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
VectorInt v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
myMap.insert(std::make_pair(0, v1));
myMap.insert(std::make_pair(1, v2));
return 0;
}
What is the bese way to take (extract/get) the vector at position x (eg 1,2...);
You can use:
auto v1=myMap[0]; //This will do a deep copy for the vector
or:
auto& v1=myMap[0]; //This will hold a reference to the vector
Be careful in the second approach because if the item has removed , the reference will be invalid.
If you want a safe option use std::map::at:
auto v1=myMap.at(0);
or:
auto& v1=myMap.at(0)
This will throw an exception (std::out_of_range) if the item is not there.
Short answer:
Best place to look for it http://en.cppreference.com/w/cpp/container/map/find
With context:
For visualisation only, I guess you should express you intention as you said in your question(get an element from the map and not "eventually" insert it as using [] for accessing a non-existing element creates it), so:
const auto& search = myMap.find(1);
if (search != example.end()) {
for(auto value: search->second) {
std::cout << value << '\n';
}
}
else {
std::cout << "Not found\n";
}
Try It Live
You can refer to the vector in the map with myMap[0] or myMap[1].
You could make an alias for either of those, e.g. auto& x = myMap[0];. Using the alias will access the vector as it is stored in the map.
To take a copy of the vector (so that you can modify the map contents without changing the copy), it is just the same as copying any other object:
auto x = myMap[0];
Note that 0 and 1 refer to the key you used in the insert call; not to the search order or the insertion order (although in your example those things all happen to be the same).

using size_type of vector in map [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
using line_nm = vector<string>::size_type;
map<string, set<line_nm>> m;
On the above code, why can't I use the code below?
map<string, set<vector<int>>> m1;
Test:
string str;
word[str].insert(5);
I got an error when I am using "m1" version.
vector<string>::size_type is an integral type.
Hence,
map<string, set<line_nm>> m;
is analogous to:
map<string, set<size_t>> m;
m[str] returns a reference to a set<size_t>, whose insert() method is expecting a size_t. That's why you can use:
m[str].insert(5);
When you use:
map<string, set<vector<int>>> m1;
m1[str] returns a reference to a set<vector<int>>, whose insert() method is expecting a vector<int>, not an int. That's why you cannot use:
m1[str].insert(5);
you can use
m1[str].insert(arg);
where arg is a vector<int> or something which can be converted to a vector<int>.
m1[str].insert(std::vector<int>{5, 10, 30});

Map size different from expected value after adding values to the map [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Basically I have a edgeCostMap of type
map<pair<int, float>, int>
and a vector of 42 vertices. I loop through the vector of vertices and add values to the map as follows:
for(int vertexIndex = 0; vertexIndex < V.size(); vertexIndex++)
{
pair<int, float> toAdd;
toAdd.first = vertexIndex;
toAdd.second = V[vertexIndex].edgeCollapseCost;
edgeCostMap[toAdd] = vertexIndex;
}
However after the loop has been finished and I print out the map contents as follows:
for(map<pair<int, float> ,int>::iterator it = edgeCostMap.begin(); it != edgeCostMap.end(); it++)
{
logFile<<"Vertex "<<it->second<<" has cost "<<it->first.second<<" has "<<mapVF[it->second].size()<<"neighbors"<<endl;
}
I only get back 12 statements. Is my mapping done incorrectly?
Compare function:
class comparator {
public:
bool operator()(const std::pair<int, float>& a, const std::pair<int, float>& b) const {
return a.second < b.second;
}
};
Your comparator considers two keys equal (neither less than the other) if their floats are equal. You cannot put two equal keys in a map. You probably want to use the default comparator but put the float first in the set. This will sort first on the float and second on the integer, ensuring the keys are not equal if their integers differ.

Map::insert does not work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am using this code to insert some elements to the map.
raw.insert({ std::string(name), new raw_resource(data, length) });
First element inserts succesfully, but second one does not.
Map type is
std::map<std::string, raw_resource*, compare> raw;
Comparator code
class compare
{
public:
bool operator()(std::string s1, std::string s2)
{
return (s1.compare(s2) == 0);
}
};
See the reference:
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
http://en.cppreference.com/w/cpp/container/map
An std::map takes a comparator that tells if the first argument is less than the second. Not if they are equal. Otherwise it could not build a binary tree.
You don't need to write your own comparator for std::string at all. All the comparison operators are already defined for you: http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp.