C++: What error in using STL vector - c++

I was using the topcoder C++ compiler, and although this code just run fine in Linux gcc, the topcoder compiler gave this error:
your code did not compile:
errors compiling:
Your class or method was improperly declared: In function
‘std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > _wrapper::thunk(std::string)’:
Your class or method was improperly declared:20034:
error: conversion from ‘void’ to non-scalar type
‘std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,
std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ requested
This is the code snippet where it is flagging error:
class BinaryCode {
public:
static int get_digit(char c)
{
return (c-'0');
}
void decode(string decd)
{
int i;
std::vector <int> decoded(decd.size());
std::transform(decd.begin(), decd.end(), decoded.begin(), &get_digit);
int length=decoded.size();
This is the topcoder problem description:
Definition Class:BinaryCode
Method:decode
Parameters:string
Returns:vector <string>
Method signature:
vector <string> decode(string message)
(be sure your method is public)
    

Your method signature is:
void decode(string decd)
Should be:
vector <string> decode(string message)
TopCoder compiles your code with testing code for the problem. Make sure the code you provide meets the requirements in the problem statement.

Topcoder compiler is expecting the function to be
vector <string> decode(string message)
while your function is
void decode(string message)
You are using 'void' instead of vector < string >

Try to use
using namespace std;
it fixed my problem. And also includes, it puts your code into separate file
#include <vector>
#include <string>

Related

how to view std:unordered_map member in GDB

When trying to access a member of std::unordered_map using [], I get an error:
Attempt to take address of value not located in memory.
There is a nice gdb-stl-views, except it does not support unordered_map.
Is there a similarly nice way to retrieve by key a member of unordered_map?
I think you are capable of viewing the member of std::unordered_map with an additional trivial step:
This is my test code:
#include <iostream>
#include <unordered_map>
std::string make_key(const char *input) { return input; }// The additional function to make sure you could construct the key of your map in gdb from primitive type
int main(int argc, char **argv) {
std::unordered_map<std::string, int> map = {
{"bar", 100}
};
std::cout << map.at("bar");
}
And I am using gdb 11.2 in Archlinux:
g++ -std=gnu++11 -O0 -g unordered_map_test.cpp -o unordered_map_test
gdb unordered_map_test
(gdb) p map
$1 = std::unordered_map with 1 element = {["bar"] = 100}
// Perhaps it's useless to print all key-value pairs in map if you have a large map.
// Then you could print value of specific key
(gdb) p map.at(make_key("bar"))
$2 = (std::unordered_map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::hash<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int> > >::mapped_type &) #0x55555556eed8: 100 // 100 is the value of `bar`
// If you think it's annoying that there is too much type information above, you could just print the value after you know the address of value.
(gdb) p *0x55555556eed8
$3 = 100

boost::spirit::hold_any memory corruption

I have a large code base that can use boost::any or boost::spirit::hold_any (depending on a macro definition).
hold_any seems to be compatible with boost::any (e.g. How to print boost::any to a stream? or Type erasure - Part IV) and faster (Why you shouldn’t use boost::any) but I'm experiencing several segmentation fault errors using hold_any (Boost v1.55 / 1.54 / 1.53).
This is a minimal working example that exhibits the same problem as the original code:
#include <iostream>
#include <string>
#include <vector>
#include <boost/spirit/home/support/detail/hold_any.hpp>
typedef boost::spirit::hold_any any;
typedef std::vector<any> vany;
int main()
{
vany data0, data1;
for (unsigned i(0); i < 1000; ++i)
{
std::string s("test_test_test");
data0.push_back(any(s));
}
const unsigned n(data0.size());
vany::iterator iter(data0.begin());
for (unsigned i(0); i < n; ++i)
{
std::cout << "Moving " << i << std::endl;
data1.push_back(*iter);
iter = data0.erase(iter);
}
return 0;
}
The program appears to work correctly:
changing from boost::spirit::hold_any to boost::any;
changing the content of the hold_any to a data type small enough to perform small buffer optimization (e.g. from std::string to int).
It seems strange that there could be some major bug in a widely used library such as Boost Spirit, but
I'm having a hard time finding a bug in the example;
I've tried g++ / clang++ without success.
What's wrong with the example?
You should not be using hold_any as it is in detail/hold_any.hpp for a reason.
That said, hold_any's copy-assignment appears to be broken. I've created a pull request on github with a proposed fix.
Without the fix, the following program demonstrates UB (because the compiler generates a shallow assignment operator which is preferred):
#include <iostream>
#include <string>
#include <boost/spirit/home/support/detail/hold_any.hpp>
typedef boost::spirit::hold_any any;
int main()
{
any b;
{
any a;
a = std::string("test_test_test");
b = a;
}
std::cout << "b: " << b << '\n';
}
When run under valgrind:
==11827== Invalid read of size 8
==11827== at 0x5E9D793: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std
==11827== by 0x4012FC: boost::spirit::detail::fxns<mpl_::bool_<true> >::type<std::string, char>::stream_out(std::ostream&, void* const*) (hold_any.hpp:113)
==11827== by 0x4010F5: std::basic_ostream<char, std::char_traits<char> >& boost::spirit::operator<< <char>(std::basic_ostream<char, std::char_traits<char> >&, boost::spirit::basic_hold_any<char> const&) (hold_any.hpp:368)
==11827== by 0x400FC9: main (test.cpp:17)
==11827== Address 0x8ac1650 is 0 bytes inside a block of size 39 free'd
==11827== at 0x4C2BADC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11827== by 0x5EC405E: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.18)
==11827== by 0x401204: boost::spirit::detail::fxns<mpl_::bool_<true> >::type<std::string, char>::static_delete(void**) (hold_any.hpp:89)
==11827== by 0x401328: boost::spirit::basic_hold_any<char>::~basic_hold_any() (hold_any.hpp:246)
==11827== by 0x4010B4: boost::spirit::basic_hold_any<char>::~basic_hold_any() (hold_any.hpp:245)
==11827== by 0x400FA0: main (test.cpp:15)

Unordered_map<string, int> works but Unordered_map<string, string> does not

I don't understand why the second block of code in this short example does not compile correctly. It is my understanding that the second parameter in the <> represents the value, which doesn't need to be unique. Why is the second block of code throwing a compiler error, and what do I need to do to remedy it?
// Unordered Map example .cpp
#include <stdio.h>
#include <string>
#include <cstring>
#include <unordered_map>
using namespace std;
int main(void) {
// This works as expected
unordered_map<std::string, int> m;
m["foo"] = 42;
printf("%i\n", m["foo"]);
// This this doesn't compile
unordered_map<std::string, std::string> m1;
m1["foo"] = "42";
printf("%s\n", m1["foo"]);
return 0;
}
I am compiling this code on CentOS 5.8 using
g++44 -c -Wall -std=c++0x -g map_example.cpp
and these are the errors I am getting
map_example.cpp: In function ‘int main()’:
map_example.cpp:20: warning: cannot pass objects of non-POD type ‘struct std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ through ‘...’; call will abort at runtime
map_example.cpp:20: warning: format ‘%s’ expects type ‘char*’, but argument 2 has type ‘int’
If I am having trouble with a basic c++ class such a std:string what do I need to do to have a custom class as a value, where can I find a fully implemented minimal example?
printf does not work with std::string. Either use cout << m1["foo"] or printf("%s", m1["foo"].c_str())
printf("%s\n", m1["foo"]); is C.
For c++ you should use std::cout to have both the string and the int map's values printed out as expected.
The compiler cannot do a translation for a std::string object automatically to const char* (there is no conversion to const char* by default: Why does std::string not provide a conversion to const char*?)

Error using unordered_set_of with Boost.Bimap

I'm attempting to follow this example from the documentation (see typedef for word_counter).
#include <string>
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
typedef boost::bimap
<
boost::bimap::unordered_set_of< std::string >,
std::string
> MyBimap;
Error thrown is
test.cpp:11:1: error: wrong number of template arguments (1, should be 5)
In file included from /usr/include/boost/bimap.hpp:13:0, from test.cpp:3:
/usr/include/boost/bimap/bimap.hpp:133:7: error: provided for ‘template class boost::bimaps::bimap’
test.cpp:11:10: error: invalid type in declaration before ‘;’ token
You have a typo.
Instead of
boost::bimap::unordered_set_of< std::string >,
use
boost::bimaps::unordered_set_of< std::string >,
in the template.
It will compile then.

Using templates [duplicate]

This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 8 years ago.
I have this bit of code from a stackoverflow question:
template <typename K, typename V>
bool exists_in(std::map<K,V> const& haystack, K const& needle)
{
return haystack.find(needle) != haystack.end();
}
Being a new user of templates, I still understand what is going on here. Only, I can't seem to apply it.
I have defined
class Varinfo; // meta information about vars
std::map<std::string,VarInfo*> g_varMap; // a map between var names and meta-info
In my main c++ code I have this statement:
// various other uses of g_varMap that don't cause errors then
if ( exists_in( g_VarMap, "fred" ) )
that generates this error.
undefined reference to `bool exists_in<std::basic_string<char,
std::char_traits<char>, std::allocator<char> >,
VarInfo*>(std::map<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, VarInfo*, std::less<std::basic_string<char,
std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> > const, VarInfo*> > > const&, std::basic_string<char,
std::char_traits<char>, std::allocator<char> > const&)'
which I completely do not understand.
Can someone tell me why this is complaining? What bitof template knowledge am I missing? I have tried various casting operations on the variable returned by and sent to exists_in() including a std::string( "fred" ). Nothing helped. Some just generated even more meaningless errors.
Undefined reference means it cannot find the definition in any object file. This is a linker error. You need to define the template method within the header file and not in a separate cpp file.
Your code looks okay, I made a rough approximation, you can see it here: http://codepad.org/UvgeTIoC
If your function were available before the point of call you would have no problem. bear in mind that it is template code, so the full implementation has to be included either directly or indirectly:
#include <map>
#include <iostream>
template <typename K, typename V>
bool exists_in(std::map<K,V> const& haystack, K const& needle)
{
return haystack.find(needle) != haystack.end();
}
int main()
{
std::map<int, int> m{{1,1},{2,2}};
std::cout << std::boolalpha;
std::cout << exists_in(m,2) << "\n";
}
output true.