I'm extracting a tuple with auto [...] but I'm only using some of the tuple coordinates.
I wanted to know if there is some elegant way to avoid the unused-variable compiler warning?
Here is my code.
#include <iostream>
#include <vector>
#include <tuple>
int main(int argc, char **argv)
{
std::vector<std::tuple<char,float,int>> myvec;
myvec.push_back(std::make_tuple('a',3.5,8));
myvec.push_back(std::make_tuple('b',1.5,4));
auto [c,f,_] = myvec[1];
std::cout << "char float is " << c << " " << f << "\n";
return 0;
}
And here is the compilation line + warning:
$ g++ -Wall -std=c++17 main.cpp -o main
main.cpp: In function ‘int main(int, char**)’:
main.cpp:10:13: warning: unused variable ‘_’ [-Wunused-variable]
auto [c,f,_] = myvec[1];
^
(I used a Haskell-like variable _ to self document the fact that the last int is a don't-care value).
Related
I want to convert a Node object from yaml-cpp to a std::string. I keep getting an error that says it cannot find the right overloaded operator <<.
Here's my code:
#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>
using namespace std;
int main(int argc, char* argv[]) {
YAML::Node myNode;
myNode["hello"] = "world";
cout << myNode << endl; // That works but I want that not to stdout
string myString = "";
myNode >> myString; // Error at this line
cout << myString << endl;
return 0;
}
The error is
src/main.cpp:13:12: error: invalid operands to binary expression ('YAML::Node' and 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char>>')
[somefile] note: candidate function template not viable: no known conversion from 'YAML::Node' to 'std::byte' for 1st argument
operator>> (byte __lhs, _Integer __shift) noexcept
^
[A bunch of these 10+]
Using clang++ -std=c++20 -I./include -lyaml-cpp -o prog main.cpp
Please help me find out!
Actually needed to create an stringstream and then convert it to an normal string:
#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>
using namespace std;
int main(int argc, char* argv[]) {
YAML::Node myNode;
myNode["hello"] = "world";
stringstream myStringStream;
myStringStream << myNode;
string result = myStringStream.str();
cout << result << end;
return 0;
}
Output:
hello: world
I am trying to convert std::string_view to float without an intermediate conversion to std::string (which will cause extra heap allocation) with a C++20 compiler.
#include <iostream>
#include <charconv>
int main() {
std::string_view s = "123.4";
float x;
std::from_chars(s.data(), s.data() + s.size(), x);
std::cout << x << std::endl;
}
But I am unable to compile this code:
error: no matching function for call to 'from_chars(std::basic_string_view<char>::const_pointer, std::basic_string_view<char>::const_pointer, float&)'
What I am doing wrong?
GCC's C++ standard library implementation first supported std::from_chars for float in GCC 11.1. 10.x won't support it.
Since you're not checking for success, and you know your string is null-terminated, you can use atof() instead, which is similarly unsafe. If you want proper checking for parsing errors, use strtof, which will give you similar information to from_chars as to whether the input matched properly:
#include <iostream>
#include <cstdlib>
int main() {
std::string_view s = "123.4";
char * end;
float x = std::strtof(s.data(), &end);
if (end != s.data() + s.size())
{
std::cout << "Parse error";
}
else
{
std::cout << x << std::endl;
}
}
If and only if you know that your string view is null terminated, you can use this
float x = static_cast<float>(atof(s.data()));
Look into charconv header. For example GCC have next guard in it
#if defined __cpp_lib_to_chars || _GLIBCXX_HAVE_USELOCALE
So it can be not implemented, or your compiler not configured to use at least C++ 17 standard. I.e. no -std=c++20 for GCC and Clang or /std:c++latest for Microsoft VC++ command line options passed to your compiler, or your implementation i.e. port not implementing this functionality and not fully implement a standard.
You always can replace from_chars with strtof c function.
For example:
#include <iostream>
#include <string_view>
#include <system_error>
#include <cmath>
#include <charconv>
#include <cstdlib>
int main(int argc, const char** argv)
{
std::string_view sv("12.345678");
#ifdef __cpp_lib_to_chars
float result = NAN;
auto conv_ret = std::from_chars(sv.data(), (sv.data() + sv.size()), result);
std::error_code ec = std::make_error_code(conv_ret.ec);
#else
char *endp = nullptr;
float result = std::strtof(sv.data(), &endp);
std::error_code ec;
if (errno == ERANGE) {
ec = std::make_error_code(std::errc::result_out_of_range);
}
#endif
if(ec) {
std::cerr << ec.message() << std::endl;
return ec.value();
}
std::cout << "Float: " << result << std::endl;
return 0;
}
error: no matching function for call to 'from_chars(std::basic_string_view<char>::const_pointer, std::basic_string_view<char>::const_pointer, float&)'
Tried following code based on above error:
#if defined(CYGWIN_NT) || defined(AIX71) || defined(SUNOS)
#include <iostream>
using namespace std;
#elif defined(LINUX) || defined(HPUX11)
#include <iostream.h>
#else
#error handle iostream/iostream.h error.
#endif
#include <charconv>
int main()
{
string_view s = "123.4";
// Always better to initialize.
float x = 0.0f;
from_chars(s.data(), s.data() + s.size(), x);
cout << x << endl;
return 0;
}
// Sample compilation:
// echo g++ -Wall 73333331.cpp -D$(uname -s | sed "s/-[0-9].*.[0-9].*-[0-9].*//;") -std=c++20 -o ./a.out
// g++ -Wall 73333331.cpp -DCYGWIN_NT -std=c++20 -o ./a.out
// ./a.out
// 123.4
I wonder how to use ICU library iterators with STL. For instance, what if we decided to output all permutations of a string?
With std::string it looks like the following:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
static void _usage(const char *executable)
{
cout << "Usage: " << executable << " <string>" << endl;
}
int main (int argc, char const* argv[]) {
if (argc < 2) {
cerr << "Target string expected" << endl;
_usage(argv[0]);
return 1;
}
string s(argv[1]);
do {
cout << s << endl;
} while (next_permutation(s.begin(), s.end()));
return 0;
}
I tried to do the same using ICU:
#include <unicode/unistr.h>
#include <unicode/uchriter.h>
#include <unicode/ustdio.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
static void _usage(const char *executable)
{
cout << "Usage: " << executable << " <string>" << endl;
}
int main (int argc, char const* argv[]) {
if (argc < 2) {
cerr << "Target string expected" << endl;
_usage(argv[0]);
return 1;
}
UnicodeString ustr(argv[1]);
UChar *uc = ustr.getBuffer(-1);
int32_t len = u_strlen(uc);
UCharCharacterIterator iter_start(uc, len);
UCharCharacterIterator iter_end(uc, len, len - 1);
do {
// XXX
} while (next_permutation(iter_start, iter_end ));
return 0;
}
But it fails to compile:
x86_64-pc-linux-gnu-g++ -I/usr/include -licuio -licui18n -licuuc -licudata permute2.C -o permute2
In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/algorithm:63:0,
from permute2.C:4:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h: In function ‘bool std::next_permutation(_BIter, _BIter) [with _BIter = icu_49::
UCharCharacterIterator]’:
permute2.C:31:49: instantiated from here
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3531:7: error: no match for ‘operator++’ in ‘++__i’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3535:7: error: no match for ‘operator--’ in ‘--__i’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3540:4: error: no match for ‘operator--’ in ‘--__i’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3541:4: error: no match for ‘operator*’ in ‘*__ii’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3541:4: error: no match for ‘operator*’ in ‘*__i’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3544:8: error: no match for ‘operator--’ in ‘--__j’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.4/include/g++-v4/bits/stl_algo.h:3544:8: error: no match for ‘operator*’ in ‘*__i’
...
What's the proper way to make use of STL with ICU? Extend the UCharCharacterIterator class and provide code for all these operators?
/*
* File: main.cpp
* Author: c1004527
*
* Created on February 15, 2012, 10:25 PM
*/
#include <stdlib.h>
#include <ctime>
#include <time.h>
#include "CardClass.h"
#include "PlayerClass.h"
/*
*
*/
int main(int argc, char** argv)
{
srand(time(0));
CardClass deck;
PlayerClass player[4];
deck.ShuffleCards();
deck.Print();
for(int i = 0; i < DECK_SIZE; i++)
{
player[i%4].AddACard(deck.DealCards());
}
for(int i = 0; i < 4; i++)
{
player[i].SortCard();
}
for(int i = 0; i < 4; i++)
{
cout << endl << endl
<< "Player "<< i+1 << endl
<< player[i];
}
return (0);
}
The error is:
**** Internal Builder is used for build
**** g++ -O0 -g3 -Wall -c -fmessage-length=0 -o OLA3\OLA3\main.o ..\OLA3\OLA3\main.cpp
..\OLA3\OLA3\main.cpp: In function 'int main(int, char**)':
..\OLA3\OLA3\main.cpp:17:17: error: 'time' was not declared in this scope
Build error occurred, build is stopped
Time consumed: 114 ms.
Everything else compiles completely fine but that. I use minGW and it compiles hello world with no problem.
Because you've included <ctime>, time is going to be defined in the std namespace.
Therefore, you need to use a fully-qualified reference: std::time.
That's what this error is telling you:
error: 'time' was not declared in this scope
I am trying to use sgi hash_map.
#include <list>
#include <iostream>
#include <string>
#include <map>
#include <cstring>
#include <tr1/unordered_map>
#include <ext/hash_map>
using namespace std;
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};
int main()
{
hash_map<const char*, int, hash<const char*>, eqstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
cout << "september -> " << months["september"] << endl;
cout << "april -> " << months["april"] << endl;
cout << "june -> " << months["june"] << endl;
cout << "november -> " << months["november"] << endl;
}
on gcc4.2 I am getting the error
listcheck.cc: In function 'int main()':
listcheck.cc:22: error: 'hash_map' was not declared in this scope
listcheck.cc:22: error: expected primary-expression before 'const'
listcheck.cc:22: error: expected `;' before 'const'
listcheck.cc:24: error: 'months' was not declared in this scope
while the same code compile with 3.4.
Use <unordered_map>. hash_map was a vendor specific extension, replaced by unordered_map.
The include file <ext/hash_map> refers to the GNU extension hash map class and this is declared in namespace __gnu_cxx. You can either explicitly qualify the template name or add:
using namespace __gnu_cxx;
using namespace __gnu_cxx; removed the compilation error.
using
#include <hash_map>
gives this warning and removing gives a compilation error
In file included from /usr/include/c++/4.4/backward/hash_map:59,
from listcheck.cc:6:
/usr/include/c++/4.4/backward/backward_warning.h:28:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, consult the file backward_warning.h. To disable this warning use -Wno-deprecated.
after removing
#include <hash_map>
g++ listcheck.cc
listcheck.cc: In function ‘int main()’:
listcheck.cc:20: error: ‘hash_map’ was not declared in this scope
listcheck.cc:20: error: expected primary-expression before ‘const’
listcheck.cc:20: error: expected ‘;’ before ‘const’
listcheck.cc:21: error: ‘months’ was not declared in this scope