std::map.operator[] not working with global maps - c++

Can someone tell me how I can make use of std::map.operator[] to get the value of a const std::map ?
For example:
file.h
#ifndef _FILE_H
#define _FILE_H
#include <map>
#include <string>
const std::map<std::string,std::string> STRINGS= {
{"COMPANY","MyCo"}
,{"YEAR","2022"}
};
#endif
file.cpp
#include "cpp_playground.h"
#include <iostream>
int main (void){
std::cout<< "Code by "<< STRINGS["COMPANY"] << " " << STRINGS["YEAR"] << std::endl;
}
With Visual Studio 2015 I get this error, but I can't interpret it
Severity Code Description Project File Line Suppression State
Error C2678 binary '[': no operator found which takes a left-hand operand of type 'const std::map<std::string,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion) cpp_playground d:\user\documents\visual studio 2015\projects\cpp_playground\cpp_playground.cpp 10

The operator[] in std::map is defined to return a reference to the object with the given key - or create it, if it doesn't exist, which modifies the map, that's why it's not a const method. There is no const version of that operator, that's why you get the shown error.
Use std::map's at(...) function for access-only. Note that it throws a std::out_of_range exception if the given key is not contained in the map; in C++20 or later you can use contains() to check whether the given key exists.

Related

Searching for files with specific extension - using recursive_directory_iterator - <filesystem> library

I am trying to search for files with certain extensions in a directory, using the "recursive_directory_iterator" function inside library.
I am using Visual Studio Express 2017.
I am following the code in this answer:
https://stackoverflow.com/a/47975458/4145697
Here is my code:
#include <windows.h>
#include <iostream>
#include <filesystem>
#include <string>
void get_list_of_files(void)
{
std::string constructed_path_str_dbg = "C:\\Cpp_trials\\Trials\\Debug\\baseline\\cpp_files_trial";
std::string ext(".sample");
for (auto& p : fs::recursive_directory_iterator(constructed_path_str_after))
{
if (p.path().extension() == ext()) // errors E0980 and C2064
std::cout << p << '\n'; // errors E0349 and C2679
}
}
But I am having the following compilation errors:
E0980 call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
E0349 no operator "<<" matches these operands
C2064 term does not evaluate to a function taking 0 arguments
C2679 binary '<<': no operator found which takes a right-hand operand of type 'const std::filesystem::directory_entry' (or there is no acceptable conversion)
According to the code you provided, I tested and modified it.
Change constructed_path_str_after to constructed_path_str_dbg
Change ext() to ext
The following are my test results:
#include <fstream>
#include <iostream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
int main()
{
std::string constructed_path_str_dbg = "C:\\Cpp_trials\\Trials\\Debug\\baseline\\cpp_files_trial";
std::string ext(".txt");
for (auto& p : fs::recursive_directory_iterator(constructed_path_str_dbg))
{
if (p.path().extension() == ext)
std::cout << p << '\n';
}
return 0;
}
I hope to know why you would use constructed_path_str_after, because this is related to your problem solving. I can only speculate on your needs based on the existing code.

Insertion operator is not working with vector and I don't know why

So I was starting to write my code and I was going to test to see if I still remember how to cast, until I get a red line under my operator.
This is the compiler error:
Error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' (or there is no acceptable conversion) (12)
I honestly never had a problem with outputting a string/vector so I do not know how to fix this. Can someone please tell me how to fix this. It would also be awesome if you could tell me what is wrong with the code.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string>hello;
hello.push_back("9");
for (auto i : hello)
cout << i << " "; <-- The first operator is underlined. Why?
return 0;
}
You need one more include in your program:
#include <string>
While <iostream> does declare/define some string related functions, not all of them.
With some compilers, the iostream header incldues string internally, but that isn't required by the standard - and Visual Studio doesn't, that's why you receive this error.

C++ cout errors whenever it tries to print a function variable [duplicate]

This question already has an answer here:
Error when i do not include string header file in c++
(1 answer)
Closed 9 years ago.
I can use cout to print a normal variable just fine, but whenever I try to print a function variable(in this case, string input) the compiler shoots out the error:
C2679: binary '<<' : no operator found which takes a right-hand
operand of type 'std::string' (or there is no acceptable conversion)
I have posted my code below. Is there anything that I am doing wrong?(I am using the C++ version of Eclipse)
Here's my code so far:
#include <iostream>
using namespace std;
void println(string text) {
cout << text << endl;
}
int main() {
int test = 5;
cout << test;
return 0;
}
If you want to use std::string, you need to include <string>! The type may be declared or even defined because it is used by the IOStream classes but the implementation may choose not to include the entire header. In your code it seems you got a definition of std::string but not the declaration of its output operator.
Operator << for class std::basic_string are declared in header <string>. So you need to include it in your program that the compiler will know about it.

STL Map error C2679 in C++

im having a problem when trying to print out pairs of int & strings in an STL Map:
this is the code im using:
#include <iostream>
#include <utility>
#include <map>
using namespace std;
typedef map<int,string> intID;
int main(){
intID ID;
ID.insert(pair<int,string>(123,"studentname1"));
ID.insert(pair<int,string>(124,"studentname2"));
ID.insert(pair<int,string>(122,"studentname3"));
intID::iterator IDIter;
for(IDIter = ID.begin();IDIter != ID.end();++IDIter){
cout <<"ID: " << IDIter->first <<", Name: " << IDIter->second << endl;
}
}
The error occurs at the ", Name: " << IDIter->second part, the << is underlined saying "no operator matches these operands"
the compile error is:
Error 1 error C2679: binary '<<' : no operator found which takes a
right-hand operand of type 'std::string' (or there is no acceptable
conversion)
Im trying to print out the second member of the pair (studentname)
I'm new to STL mapping so i'm not sure what i'm doing wrong, what do i need to change?
You need to include the <string> header. You've only been able to use the std::string type by incidental inclusion from other headers. You can't rely on this. Including <string> will also bring in the overloads of operator<< that allow you to output strings.

Chain value of string variable with some text and print it to standard output in C++

I want to do something really simple: I have function that has string parameter and I want to chain it to some constant string, then output result to console like this:
void test(string s){
cout << "Parameter of this function was: " << s;
}
In other languages chaining like this works, but in C++ the compiler is unhappy: error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
You probably forgot to #include <string> or #include <iostream>.
What version of Visual Studio are you using? Your code sample is correct C++ (as long as you have the appropriate "using namespace std;").
Putting similar code through g++ works fine.