EDIT: Sorry, i didn't put any result. I expected to remove the (10th, 11th), then the (20th, 21st), then the (30th, 31st) and so forth but instead I get this http://imgur.com/TbVmLo4
I have a vector composed by several vectors of the same size and i want to get rid of part of their end using remove if and a lambda function but there seems to be a displacement in the removal. Here is the code that I am running:
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <typeinfo>
int main()
{
int sizeOfSpectrum=10;
int desiredSizeOfSpectrum=8;
int count=-1;
std::vector<int> v(100);
std::iota (std::begin(v), std::end(v), 0);
auto newend=std::remove_if(v.begin(),v.end(),[&](int i)->bool{
count++;
int temp=count%sizeOfSpectrum;
bool test=(temp) > desiredSizeOfSpectrum;
return ( test);
});
v.erase(newend, v.end());
std::cout << "\n";
std::cout << "v[i]: \n";
for(int i : v)std::cout <<v[i]<<": ";
std::cout << "\n";
return 0;
}
The problem is in this line:
for(int i : v)std::cout <<v[i]<<": ";
When this line runs, i is given the value of the contents of each element of the vector. You are treating this as an index into the vector, rather than the value.
Instead use:
for(int i : v)
std::cout <<i<<": ";
Note: you still won't get quite the output you are after, but this should give you enough to work that out for yourself.
Related
I would like to print the strings at the top of columns with a 1 x 3 array.
I have edited this simple function several times, and this produces the least errors. New to C++, reading Deital Chap 6 Recursive.
What am I missing? I started with half brackes around strings, and brackets seemed to produce less errors.
Here is the code:
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main() {
array a[1][3] = ["Car" "Hours" "Charge"]
cout<< a << endl;
}
Terminal produces errors as such:
parking_charges_6_12.cpp: In function ‘int main()’:
parking_charges_6_12.cpp:8:7: error: missing template arguments before ‘a’
8 | array a[1][3] = ["Car" "Hours" "Charge"]
^
This should work:
#include <array>
#include <iostream>
#include <string>
int main(){
std::array<std::string, 3> headlines = {"Car", "Hours", "Charge"};
for( auto const& elem : headlines ){
std::cout << elem << "\t";
}
}
It should be curly braces {} in the initializer, not []. And you need a comma between each element.
On the other hand, in later C++ revisions array can detect the type and number of elements, so you don't have to give that.
#include <iostream>
#include <array>
using namespace std;
int main() {
array a = {"Car", "Hours", "Charge"};
for (auto& item : a)
cout<< item << endl;
}
How about something like this:
#include<iostream>
using namespace std;
int main() {
string data[3] = {"Car", "Hours", "Charge"};
for (int i = 0; i < 3; i++)
cout << data[i] << " ";
}
Obviously it is not using the array header, but it's a working example. If you do need to use the array header, you can try something like :
#include <array>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
array<string, 3> ar3 = {"Car", "Hours", "Charge"};
cout << ar3.size() << endl;
for (auto i : ar3)
cout << i << ' ';
return 0;
}
You can see it working online here
I try to build an std::string in the form of "start:Pdc1;Pdc2;Pdc3;"
With following code I can build the repeated "Pdc" and the incremental string "123" but I'm unable to combine the two strings.
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>
int main()
{
std::ostringstream ss;
std::string hdr("start:");
std::fill_n(std::ostream_iterator<std::string>(ss), 3, "Pdc;");
hdr.append(ss.str());
std::string v("abc");
std::iota(v.begin(), v.end(), '1');
std::cout << hdr << std::endl;
std::cout << v << std::endl;
std::cout << "Expected output: start:Pdc1;Pdc2;Pdc3;" << std::endl;
return 0;
}
How can I build this string? Preferable without a while or for loop.
The expected output is: start:Pdc1;Pdc2;Pdc3;
std::strings can be concatenated via their operator+ (or +=) and integers can be converted via std::to_string:
std::string res("start:");
for (int i=0;i<3;++i){
res += "Pdc" + std::to_string(i+1) + ";";
}
std::cout << res << "\n";
If you like you can use an algorithm instead of the handwritten loop, but it will still be a loop (your code has 2 loops, but only 1 is needed).
Code to generate your expected string, though with a small for loop.
#include <iostream>
#include <string>
#include <sstream>
std::string cmd(const std::size_t N)
{
std::ostringstream os;
os << "start:";
for(std::size_t n = 1; n <= N; ++n) os << "Pdc" << n << ";";
return os.str();
}
int main()
{
std::cout << cmd(3ul);
return 0;
}
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
}
Why is this code giving up an error? I am unable to identify the cause of the error.
Error: No Match for operator !=....
First of all, you are trying to compare int with the iterator of vector.
for(int i=0; i!=test.end();i++)
{
cout << test[i];
}
Here, the test.end() returns the iterator. There is no overloaded operator!= which can compare integer (int i = 0) with that iterator (test.end()).
So your loop should look more like:
for (std::vector<string>::iterator i = test.begin(); i != test.end(); i++)
{
cout << *i;
}
You can replace std::vector<string>::iterator with auto, if using C++11 or newer.
The next thing, you included <string.h> which contains old functions such as: strlen, strcpy. Similarly, <cstring> contains C-style strings.
If you want to you use operator<<, so if you want to write:cout << then you have to do: #include <string>.
As already mentioned, the problem is, that you try to compare an integer with an iterator in the "middle" of your for statement. Try this instead, it's more intuitive from my point of view
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
vector<string> test;
test.push_back("yasir");
test.push_back("javed");
for(int i=0; i<test.size();++i)
{
cout << test[i];
}
}
I have a string array of size 5, and I have n elements in it. How could I determine n? I have tried sizeof(array)/sizeof(array[0]), but that returns the size of the array, which is 5. My code is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string array[5];
array[0] = "pie";
array[1] = ":P";
array[2] = "YELLOW";
cout << sizeof(array)/sizeof(array[0]);
}
I have a string array of size 5, and I have n elements in it. How could I determine n?
n is 5. Your array has 5 elements, because you declared it to be an array of 5 strings. array[3] and array[4] are just empty strings (""), but they're still there, and completely valid elements.
If you want to count how many non-empty strings your array has, you could use e.g. std::count_if with a lambda:
int numberOfNonEmptyStrings = count_if(begin(array), end(array),
[](string const& s) { return !s.empty(); });
or a handmade loop:
int numberOfNonEmptyStrings = 0;
for (auto const& s : array)
if (!s.empty())
++numberOfNonEmptyStrings;
A built-in array, called a raw array, has no support for a dynamic length. It has a fixed length. For a declared array that fixed length can be found in many ways, including the not-very-safe C idiom you used.
std::vector<Itemtype> from the standard library (header <vector>), manages a raw array plus a dynamic length. And that's apparently exactly what you need. The internal array, called the vector “buffer”, is automatically replaced with a larger one as needed, so you do not even have to specify the capacity up front – you can just add items to the vector.
Adding items to a vector is usually done via a method called push_back, and finding the current number of items, the length, is usually done via the size method, like this:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> a;
a.push_back( "pie" );
a.push_back( ":P" );
a.push_back( "YELLOW" );
cout << a.size() << endl;
}
But since std::vector supports initialization via a brace initialization list, you do not have to use push_back for known initial items:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> a = { "pie", ":P", "YELLOW" };
cout << a.size() << endl;
}
A final refinement is to use const if it's not intended for that vector to change. This makes it easier to reason about the code. With const you see up front that none of all that code below will be changing this vector, so you can be sure of what values it provides at any point:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> const a = { "pie", ":P", "YELLOW" };
cout << a.size() << endl;
}
Disclaimer: code not touched by compiler's dirty hands.
Where you really want a fixed size array, you should preferably use std::array<Itemtype>. It works well with a range-based loop. And it has a size method, like vectors, so you can do things like this:
#include <algorithm> // std::count
#include <iostream>
#include <string> // std::string
#include <array> // std::array
using namespace std;
int main()
{
array<string, 5> const a = { "pie", ":P", "YELLOW" };
cout << "Fixed size: " << a.size() << endl;
int const n_empty = count( begin( a ), end( a ), "" );
cout << "Non-empty strings: " << a.size() - n_empty << endl;
}
You need to make a variable which holds the value of how many strings you have stored so far, and update that variable when you store a string.
Alternatively you could use a standard container instead of a C-style array:
#include <vector>
// ... in main
vector<string> array;
array.push_back("pie");
array.push_back(":P");
array.push_back("YELLOW");
cout << array.size() << '\n';
Standard class std::string has methods size and length that return the number of characters in a string.
For example relative to your code snippet
array[0] = "pie";
array[1] = ":P";
array[2] = "YELLOW";
array[0].size() will return 3,
array[1].size() will return 2,
array[2],size() will return 6
Is the first element of arr1 getting added?
cout is giving me an error. What am I doing wrong?
#include <iostream>
using std::cin; using std::cout; using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <cstddef>
using std::size_t;
int main ()
{
vector <int> ivec1; //defines a vector named ivec1 to hold values not yet defined
int arr1 [5] = {10, 20, 30 , 40, 50}; // defines array named arr1 with 5 values
ivec1.push_back (arr1 [0]);
cout << ivec1 << endl;
return 0;
}
The answer is quite simple: The operation you are invoking is simply not defined. The IO stream library is blissfully unaware of C++ standard library containers (besides std::string) and does not know how to print them. You will need to do that yourself.
std::vector<int> v;
for(auto& x : v)
std::cout << v << " "; // print each element
std::cout << std::endl; // and a linebreak
I guess cout is not able to work with vectors. I'd implement something like this (I'm sorry for my C++ I didn't write in C++ since 2006...
#include "stdafx.h"
#include <iostream>
using std::cin; using std::cout; using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <cstddef>
using std::size_t;
void fillVector(int output[], vector<int>& input, int size)
{
for(int i=0;i<size; i++)
{
input.push_back(output[i]);
}
}
void printVector(vector<int>& input)
{
for(int i=0; i<input.size(); i++)
{
cout << input.at(i);
if(i!=input.size()-1)
{
cout << ",";
}
}
cout << endl;
}
int main ()
{
vector <int> ivec1; //defines a vector named ivec1 to hold values not yet defined
int arr1 [5] = {10, 20, 30 , 40, 50}; // defines array named arr1 with 5 values
int sz = sizeof(arr1) / sizeof(int);
fillVector(arr1, ivec1, sz);
printVector(ivec1);
return 0;
}