#include <iostream>
#include <vector>
#include <iterator>
#include <iostream>
#include <cmath>
#include <string>
#include <utility>
#include <cstring>
#include <list>
using std::vector;
using std::cout;
using std::list;
using std::endl;
using std::string;
using namespace std;
template <typename T>
void showContents(T& input)
{
typename T::iterator it;
for (it=input.begin(); it != input.end(); it++)
{ cout << *it << " "; }
cout << endl;
}
int main()
{
int B[10] = {0,1,2,3,4,5,6,7,8,9};
cout<< "The first array is: "<< "\n";
int i;
for (i = 0; i<10; i++)
{cout<< B[i]<< " ";}
vector<int> KVec(B,B+10);
cout << "\n \n" << "The first vector is: " << endl;
showContents(KVec);
list<int> BList(B,B+10);
cout << "\n" << "The first list is: " << endl;
showContents(BList);
int BCopy [10];
cout<< "\n" <<"The second array is: "<< endl;
for(int i = 0; i <10; i++)
{
BCopy[i] = B[i];
BCopy[i] += 2;
cout<< BCopy[i]<< " ";
}
vector<int> KVec2(KVec);
cout<< "\n \n" << "The second vector is: "<< endl;
for (int i = 0; i<KVec2.size(); i++){
KVec2[i] += 3;
}
showContents(KVec2);
cout<< "\n" << "The second list is: "<< endl;
std::list<int> BList2 (BList);
for (std::list<int>::iterator b = BList.begin(); b!=BList.end(); ++b)
{
( *b += 5 );
showContents(BList2);
}
This is the code I have. I was able to correctly copy all the arrays, vectors , and lists and increasing the values of those accordingly. The only one I have not been able to increment in the list. My goal is to increment all the elements of the second list by 5. I have been using mulitple references to try and do it but I have tried everything and can not get it to work. Below I have my latest attempt at trying to increment all the values but that doesn't seem to work either so now I need help. That is the only thing left to do in this assignment so any help would be appreciated. Thank you.
Since my comment fixed your problem, I am converting it into an answer.
You copy constructed BList2 using values from BList (I am changing to brace initialization to avoid Most vexing parse). But then, you are iterating over values of BList again. Also, you don't need parentheses around *b += 5. Finally, your showContents function is probably meant to be outside of the loop.
std::list<int> BList2 {BList};
for (std::list<int>::iterator b = BList2.begin(); b != BList2.end(); ++b)
{
*b += 5;
}
showContents(BList2);
Related
The task is interchange two parts of a word, which contains the dash (i.e we have 1237-456 but should transform it into 456-1237). Here`s my code, it runs but doesnt shows results as a string is out of range and i dk why. It happens in the 1st for, the second iteration ends in the error+ it happens when strlen is 5 and more. The code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int u = 0, y = 0;
string first, second;
int i = 0;
string word;
cout << "Enter the text: " << endl;
getline(cin, word);
int l = size(word);
int f = word.find('-');
cout << "The word has " << l << " characters" << endl << endl;
for (int i = 0; i < f; i++) {
first[i] = word[i];
}
for (int i = f + 1; i < l; i++) {
second[y] = word[i];
y++;
}
cout << endl << second << " - " << first << endl;
}
first and second will not have memory allocated to them. They are initialized as strings of size 0. And for this case I would just use iterators instead of indices (though they could work too, but then you need more manual work to allocate enough room for the target strings and all).
All in all I think your code is mixing 'c' and 'c++' style a bit so here is my example:
#include <algorithm> // for find
#include <iostream>
// #include <cstdlib> // <<== this is "c" not C++
// using namespace std; <<== unlearn this
int main()
{
std::string word{ "Mississippi-delta"};
// std::string has a lenght function use that
std::cout << "The word has " << word.length() << " characters\n";
// "it" will be an iterator to the location of '-' (if any)
auto it = std::find(word.begin(), word.end(), '-');
// it points (beyond) the end of the word if no '-' is found
if (it == word.end())
{
std::cout << "no '-' found in word";
}
else
{
std::string first{ word.begin(),it };
++it; // skip '-'
std::string second{ it,word.end() };
std::cout << second << "-" << first << "\n";
}
return 0;
}
Instead of accessing the elements of first and second, just try using .push_back() to add characters from word.
I want to increase the size of the array of string after declaring it once, how can it be done. I need to increase the size in the following code..
#include<iostream>
using namespace std;
#include<string>
int main()
{
int n;
string A[] =
{ "vaibhav", "vinayak", "alok", "aman" };
int a = sizeof(A) / sizeof(A[0]);
cout << "The size is " << a << endl;
for (int i = 0; i < a; i++)
{
cout << A[i] << endl;
}
cout << "Enter the number of elements you want to add to the string"
<< endl;
cin >> n;
cout << "ok now enter the strings" << endl;
for (int i = a; i < n + a; i++)
{
cin >> A[i];
}
a = a + n;
A.resize(a); // THIS KIND OF THING
for (int i = 0; i < a; i++)
{
cout << A[i] << endl;
}
return 0;
}
Plain and simple: you cannot.
You can get a larger array, copy all your stuff over and use that instead. But why do all that, when there is a perfectly good class already there, doing it all for you: std::vector.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};
std::cout << "The size is " << A.size() << std::endl;
for(string s : A)
{
std::cout << s << std::endl;
}
// want to enter more?
sd::string more;
std::cin >> more;
A.push_back(more);
std::cout << "The size is " << A.size() << std::endl;
for(string s : A)
{
std::cout << s << std::endl;
}
return 0;
}
Convert your code over to use std::vector and this problem becomes much easier to solve.
#include<iostream>
#include<string>
#include<vector>
int main(){
int n;
std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};
int a = A.size();
std::cout << "The size is " << a << std::endl;
//Prefer Range-For when just iterating over all elements
for(std::string const& str : A){
std::cout << str << std::endl;
}
std::cout << "Enter the number of elements you want to add to the string" << std::endl;
std::cin >> n;
std::cout << "ok now enter the strings" << std::endl;
for(int i = 0; i < n; i++ ) {
//emplace_back automatically resizes the container when called.
A.emplace_back();
std::cin >> A.back();
//If you're using C++17, you can replace those two lines with just this:
//std::cin >> A.emplace_back();
}
for(std::string const& str : A){
std::cout << str << std::endl;
}
return 0;
}
Also, don't use using namespace std;, since it leads to expensive to fix bugs and makes your code harder to read for other C++ programmers.
I want to increase the size of the array of string after declaring it
once, how can it be done.
It cannot be done. Use std::vector if the element count isn't known at compile time or can change dynamically. It even has a resize member function named exactly like the one in your code.
You cannot increase the size of a Raw Array, you could use an std::vecto<std::string> as this type of array can grow at runtime.
However, you could also create a class that will store an array of string and create your own implementation to resize the raw array. Which would be creating a bigger array and copying all the other values over, then setting the class array to the new array (or just return it)
Here is the code:
#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdio>
int main(int argc, char *argv[]) {
const unsigned int max_chars = 100;
char buffer[max_chars];
std::cin.getline(buffer, max_chars, '\n');
unsigned int count = 0;
for (auto c : buffer) {
if (c == '\0') {
break;
}
count++;
}
std::cout << "Input: ===========" << std::endl;
std::cout << buffer << std::endl;
std::cout << "Number of chars ==" << std::endl;
std::cout << std::dec << count << std::endl;
std::cout << "==================" << std::endl;
}
This is adapted from some example code in a c++ text book deliberately dealing with c-style strings, so bear with me.
So I tried two versions of this, one with for (auto c : buffer) and the other with for (auto &c : buffer). Both seemed to work. The question is, what is the difference then?
When you use a link, you work directly with the elements of the container. Otherwise - with a copy. Try this example:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 10;
vector<int> a(n);
vector<int> b(n);
for (auto &key : a) key = rand()%10;
for (auto key : b) key = rand()%10;
for (int i = 0; i < n; i++) cout << a[i];
cout << endl;
for (int i = 0; i < n; i++) cout << b[i];
}
The first one (no &) is a value, the second one (with &) is a reference. A reference, as its name implies, "references" a value, similar to the way a pointer "points" to a value.
Try adding c = 'x'; after your if statement and trying both ways to see the difference here.
With the code below, I cannot figure out why numbs[numbs.size()] doesn't give me an appropriate response. I would assume it would give me the last item in the sorted vector, in this case it should be the largest. Yet, cout << numbs[numbs.size()]spits out garbage, e.g.
Number 1 entered. [1], smallest: 1. there are 1 elements in the vector. 1.36617e-231 is the largest.
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
double number_input = 0.0;
string unit = " ";
vector<double> numbs;
while (cin >> number_input)
{
numbs.push_back(number_input);
cout << "Number " << number_input << "entered.\n";
for(int i = 0; i < numbs.size(); ++i)
{
cout << "[" << numbs[i] << "],";
}
sort(numbs.begin(),numbs.end());
cout << "smallest: " << numbs[0] << endl;
cout << "there are " << numbs.size() << " elements in the vector.\n";
cout << numbs[numbs.size()] << " is the largest.";
}
return 0;
}
Indexes in a vector are 0-based, just as arrays are. So the last value in a vector v is v[ v.size() - 1 ] assuming v.size() > 0
I would like to see whether it is possible to see all values that we have emplaced. For example:
#include <iostream>
#include <unordered_map>
using namespace std;
int main () {
unordered_multimap<string,int> hash;
hash.emplace("Hello", 12);
hash.emplace("World", 22);
hash.emplace("Wofh", 25);
for (int i = 1; i < 10; i++) {
hash.emplace("Wofh", i);
}
cout << "Hello " << hash.find("Hello")->second << endl;
cout << "Wofh " << hash.count("Wofh") << endl;
cout << "Wofh " << hash.find("Wofh")->second << endl;
return 0;
}
The output is :
$ ./stlhash
Hello 12
Wofh 10
Wofh 9
Whereas I want the last line to show from 25,1,2... to 9. Apparently find only takes first and second pointer as first is the value and second is the corresponding value. Is there any way to do this?
The operation you need is called equal_range
Example from the cplusplus.com:
// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
typedef std::unordered_multimap<std::string,std::string> stringmap;
int main ()
{
stringmap myumm = {
{"orange","FL"},
{"strawberry","LA"},
{"strawberry","OK"},
{"pumpkin","NH"}
};
std::cout << "Entries with strawberry:";
auto range = myumm.equal_range("strawberry");
for_each (
range.first,
range.second,
[](stringmap::value_type& x){std::cout << " " << x.second;}
);
return 0;
}