displaying an iterator to a vector - c++

I am working on a project where I am placing an enum into a vector. and I was wondering how I could get functionality like such out of the vector.
for(int ii = 0; ii < thing.getSize(); ii++){
cout << "thing(" << ii << ") = " << toString(thing[ii]) << endl;
}
I've tried about 5 different ways to do this, and none of them seem to work. I have read through MSDN vector (vector::end() seemed the most helpful until it said that the operator<< wouldn't accept ii as an iterator.
can somebody help me out? the closest I think I got was
vector<int>::iterator ii;
for(ii = things.begin(); ii != things.end(); ii++){ //764
cout << "thing(" << (int)ii << "): " << toString(things[ii]) << endl; //765
}
but this throws errors that either don't make sense or I can't figure out how to solve.
1>c:\...\Project.cpp(764): error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion)
1>c:\...\Project.cpp(765): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion)
1>c:\...\Project.cpp(765): error C2679: binary '[' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion)

The correct generic way to do this is
for(std::vector<int>::const_iterator ii=things.begin();
ii != things.end(); ++ii)
{
std::cout << "thing("
<< std::distance(things.begin(), ii)
<< "): " << *ii << std::endl;
}
is by dereferencing the iterator and using std::distance to get the distance from the beginning.
further more it is generally considered bad to import an entire namespace it is better to either have explicit using statements or a preferably prefix types with it's namespace.
It is also generally preferrable to use the prefix increment operator for iterators.
Also unless you are doing some interesting formatting there is no need to apply 'toString' to an int. As it has a stream operator defined for it.

Try:
cout << "thing(" << (ii - things.begin()) << "): " << toString(*ii) << endl;

Iterators behave pretty much like pointers: they indicate the position of the value and you need to dereference them to get the value:
std::cout << *ii;

things has to be declared as:
vector < int > things;
You can enter your values into the vector like so:
things.push_back( 1 );
things.push_back( 2 );
Then you iterate like this:
for ( vector < int >::iterator i = things.begin(); i != things.end(); ++i )
{
cout << "things( " << ( i - things.begin() ) << " ): " << toString( *i ) << endl;
}

Related

Invalid operands to binary expression when using unordered_map?

I'm trying to find if my character hash table contains the first character of a string:
string minWindow(string s, string t) {
unordered_map<char, int> charFinder;
for (int i = 0; i < t.length(); ++i) {
charFinder[t[i]] = 0;
}
cout << charFinder.find(s[0]) == charFinder.end() << endl;
return "hi";
}
But I get this error for some reason. This doesn't make any sense to me. Anyone have any ideas?
Line 8: Char 14: error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'std::unordered_map<char, int, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, int> > >::iterator' (aka '_Node_iterator<std::pair<const char, int>, __constant_iterators::value, __hash_cached::value>'))
cout << charFinder.find(s[1]) == charFinder.end() << endl;
~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/cstddef:124:5:
note: candidate function template not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'std::byte' for 1st argument
operator<<(byte __b, _IntegerType __shift) noexcept
^
I cutoff the rest of the long error message.
Per Operator Precedence, operator<< has a higher precedence than operator==, so your cout expression:
cout << charFinder.find(s[0]) == charFinder.end() << endl;
Is being evaluated as if you had written it like this:
(cout << charFinder.find(s[0])) == (charFinder.end() << endl);
The compiler error is complaining about passing the std::unordered_map itself to operator<<, which is not what you intended. Look at the error message more carefully, that is exactly what it is pointing out. There is no operator<< for std::ostream that takes a std::unordered_map as input.
To fix this, you need to use parenthesis explicitly to tell the compiler what you really want, eg:
cout << (charFinder.find(s[0]) == charFinder.end()) << endl;
Otherwise, use a bool variable instead:
bool notFound = charFinder.find(s[0]) == charFinder.end();
cout << notFound << endl;
In C++20, you can use std::unordered_map::contains() instead:
cout << charFinder.contains(s[0]) << endl;
That being said, since you are not actually using the character counts at all, you should use std::set instead of std::unordered_map, eg:
string minWindow(string s, string t) {
set<char> charFinder;
for (int i = 0; i < t.length(); ++i) {
charFinder.insert(t[i]);
}
//
// alternatively:
// set<char> charFinder(t.begin(), t.end());
cout << (charFinder.find(s[0]) == charFinder.end()) << endl;
//
// alternatively:
// bool notFound = charFinder.find(s[0]) == charFinder.end();
// cout << notFound << endl;
//
// alternatively:
// cout << charFinder.contains(s[0]) << endl;
return "hi";
}
Problem is with this statement :
cout << charFinder.find(s[0]) == charFinder.end() << endl;
stream insertion operator, << has higher precedence than equality operator, ==.
The statement is same as :
((cout << charFinder.find(s[0])) == charFinder.end()) << endl;
The overloaded operator << of std::cout returns a reference to std::cout.
When compiler encounters that you are comparing a std::ostream object (std::cout) with an iterator which is returned by std::unordered_map.end() it issues an error as std::ostream does not have an overloaded operator == to compare itself with an iterator.

Ternary operator compilation

Why does this giving compilation problem at bold line?
#include<iostream>
static int i = 10;
int main() {
**(i) ? (std::cout << "First i = " << i << std::endl) : ( i = 10);**
std::cout << "Second i = " << i << std::endl;
}
Compilation message:
test.c:8: error: invalid conversion from ‘void*’ to ‘int’
Your usage of the ternary operator is a bit weird: based on the value of i, you either print something to std::cout or assign a new value to it. Those actions don't share a connection through the return value of an expression, so don't do it like this. When using the ternary operator, it's best to stay closer to its intended purpose: a short notation for two possible expressions with a dispatch based on a simple predicate. Example:
const int n = i == 0 ? 42 : 43;
Your code should look like this:
if (i == 0)
i = 10;
else
std::cout << "First i = " << i << "\n";
The reason the original snippet did not compile is that there is no common return type of the ternary operator. "Common" means that both expressions can be converted to the return type. E.g., in const int n = i == 0 ? 42 : 43; the return type is int.
The problem comes from the fact that the return values of the expressions in your conditional operator (ternary operator) (std::ofstream in the case of the std::cout ..., and int for i = 10) are incompatible and therefore the conditional operator is ill-formed. Please check the rules for return type of the conditional operator.
In this case, just use a normal conditional:
if (i)
std::cout << "First i = " << i << std::endl;
else
i = 10;

Eigen Matrix of Vector3d gives strange error

I need container of 3D vectors and tried this:
//typedef Eigen::Matrix<Vector3d, -1, 1> Field3X;
typedef Eigen::Matrix<Vector3d, Dynamic, 1> Field3X;
Field3X vecMat(3);
Vector3d v(1.0,3.0,4.0);
vecMat(0)= v;
vecMat(1) = v;
vecMat(2) = v;
cout << "Here is vecMat:\n" << vecMat << endl;
Calling cout line gives strange error:
Error 3 error C2665: 'log10' : none of the 3 overloads could convert all
the argument types d:\eigen-eigen-
5a0156e40feb\eigen\src\Core\NumTraits.h 34 1
What is better way to have array of Vector3d objects?
p.s. yes I know, I can use stl vector with alignment macro, but which one is better for faster access an manipulations?
The stream output operator << is not defined / overlaoded for the type that you want to display. You can use this instead:
for (int i = 0; i < vecMat.size(); ++i) {
cout << "Here is vecMat(" << i << "):\n" << vecMat(i) << endl;
}

Cout String and int in ternary operator

A line in my c++ code reads:
cout<<(i%3==0 ? "Hello\n" : i) ;//where `i` is an integer.
But I get this error:
operands to ?: have different types 'const char*' and 'int
How can I modify the code (with minimum characters)?
Ugly:
i%3==0 ? cout<< "Hello\n" : cout<<i;
Nice:
if ( i%3 == 0 )
cout << "Hello\n";
else
cout << i;
Your version doesn't work because the result types of the expressions on each side of : need to be compatible.
You can't use the conditional operator if the two alternatives have incompatible types. The clearest thing is to use if:
if (i%3 == 0)
cout << "Hello\n";
else
cout << i;
although in this case you could convert the number to a string:
cout << (i%3 == 0 ? "Hello\n" : std::to_string(i));
In general, you should try to maximise clarity rather than minimise characters; you'll thank yourself when you have to read the code in the future.
operator<< is overloaded, and the two execution paths don't use the same overload. Therefore, you can't have << outside the conditional.
What you want is
if (i%3 == 0) cout << "Hello\n"; else cout << i;
This can be made a bit shorter by reversing the condition:
if (i%3) cout << i; else cout << "Hello\n";
And a few more characters saved by using the ternary:
(i%3)?(cout<<i):(cout<<"Hello\n");
std::cout << i % 3 == 0 ? "Hello" : std::to_string(i);
But, as all the other answers have said, you probably shouldn't do this, because it quickly turns into spaghetti code.

C++ const casting

I am trying to print the value of a const but it is not working. I am making a return to C++ after years so I know casting is a possible solution but I can't get that working either.
The code is as follows:
//the number of blanks surrounding the greeting
const int pad = 0;
//the number of rows and columns to write
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl << "Rows : " + rows;
I am trying to print the value of 'rows' without success.
You want:
cout << endl << "Rows : " << rows;
Note this has nothing to do with const - C++ does not allow you to concatenate strings and numbers with the + operator. What you were actually doing was that mysterious thing called pointer arithmetic.
You're almost there:
cout << endl << "Rows : " << rows;
The error is because "Rows : " is a string literal, thus is a constant, and generally speaking is not modified as you may think.
Going slightly further, you likely used + (colloquially used as a concatenation operation) assuming you needed to build a string to give to the output stream. Instead operator << returns the output stream when it is done, allowing chaining.
// It is almost as if you did:
(((cout << endl) << "Rows : ") << rows)
I think you want:
std::cout << std::endl << "Rows : " << rows << std::endl;
I make this mistake all the time as I also work with java a lot.
As others have pointed out, you need
std::cout << std::endl << "Rows : " << rows << std::endl;
The reason (or one of the reasons) is that "Rows : " is a char* and the + operator for char*s doesn't concatenate strings, like the one for std::string and strings in languages like Java and Python.