I was working with vector and trying to work with erase function from vector library.
Here is my code
#include <iostream>
#include <vector>
int leftover(std::vector<int> aList)
{
// size = 1 will be termination point
if (aList.size() == 1)
{
return aList.at(0);
}
else
{
aList.push_back(aList.at(0));
aList.erase(aList.at(0));
aList.erase(aList.at(1));
return leftover(aList);
}
}
int main()
{
int x;
std::cout << "Enter a number: ";
std::cin >> x;
std::vector<int> intVector;
for (int i = 0 ; i < x; i++) {
intVector.push_back(i+1);
}
for (const int& i : intVector)
{
std::cout << i << " ";
}
std::cout << "\n";
//int leftwith = leftover(intVector);
//std::cout << leftwith << "\n";
return 0;
}
Anything with remove the element at particular position would be much appreciated.
Related
I'm attempting to print out the contents of a 2d vector in the same fashion in which they are initialized.
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<vector<int > > frontier = {{-1,0}, {1,0}, {0,-1}, {0,1}};
for (int i = 0; i < frontier.size(); i++) {
for (int j = 0; j < frontier[i].size(); j++) {
std::cout << frontier[i][j] << ", ";
}
}
cout << "End of frontier. " << endl;
/* This below is an implementation that I found online but found
no
* way to be able to implement the column reference.
*/
for (int i = 0; i < frontier.size(); ++i) {
for (int j = 0; j < col; ++j) {
cout << frontier[i + j * col] << ' ';
}
cout << endl;
}
}
This is to determine the contents of a 2d vector. So far, this code can print out every index separated by a comma. I, on the other hand, need to write code that will signify where a new vector begins.
output:
-1, 0, 1, 0, 0, -1, 0, 1,
expected output:
{{-1,0}, {1,0}, {0,-1}, {0,1}}
Here's how I might do it:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::string outerPrefix = "";
std::cout << "{";
for(const auto& outer : frontier)
{
std::cout << outerPrefix << "{";
std::string innerPrefix = "";
for(auto inner : outer)
{
std::cout << innerPrefix << inner;
innerPrefix = ",";
}
std::cout << "}";
outerPrefix = ", ";
}
std::cout << "}";
}
Output: {{-1,0}, {1,0}, {0,-1}, {0,1}}
In the first example I used a range-based for loop. If you're familiar with the concept of foreach in many languages it's basically the same thing. If you don't need an actual index variable it is safer because you don't have to worry about being off by one and indexing outside the container. It also works the same way on containers like map or set where you would need to use iterators rather than an index.
If you were to do the same thing with nested index loops like you had in your original it might look something like this:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::vector<int>> frontier = { {-1,0}, {1,0}, {0,-1}, {0,1} };
std::cout << "{";
for(size_t outer = 0; outer < frontier.size(); ++outer)
{
if (outer != 0)
{
std::cout << ", ";
}
std::cout << "{";
for(size_t inner = 0; inner < frontier[outer].size(); ++inner)
{
if (inner != 0)
{
std::cout << ",";
}
std::cout << inner;
}
std::cout << "}";
}
std::cout << "}";
}
My program can't read all of the data from my MarvelIn.txt file.
It reads about 29 spaces in, and MarvelIn.txt contains only 9 entries, then I get a runtime error.
I think I have all the syntax right, however this is the only error I have. It will not output to the output file "MarvelOut.txt".
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;
struct sstruct
{
string first, last;
string department;
int salary;
};
void init2(sstruct s[50])
{
int maxarray = 50;
sstruct init = { "Darth", "Vader", "None", 0 };
for (int i = 0; i < maxarray; i++) {
s[i] = init;
cout << "init: " <<s[i].first<<endl;
}
}
void read(sstruct s[50], int &nums)
{
int maxarray = 50;
ifstream inf("MarvelIn.txt");
int i = 0;
while (!inf.eof())
{
inf >> s[i].first >> s[i].last >> s[i].department >> s[i].salary;
cout << "read: "<<s[i].first<<s[i].last << s[i].department <<
s[i].salary << endl;
i++;
}
nums = i;
}
void avg(sstruct s[50], int &nums, double &average2)
{
int maxarray = 50;
int i;
for (i = 0; i < nums; i++)
average2 += s[i].salary;
average2 /= nums;
}
void print(sstruct s[50], int nums, double &average2)
{
int maxarray = 50;
ofstream outf("MarvelOut.txt");
int i = 0;
string temp;
outf << "the number of professors is: " << nums << endl;
cout << "the number of professors is: " << nums << endl;
outf << endl << "The average salary of the professors is: " << average2 << endl;
outf << "Advisor " << "Major " << " Department " << "Salary " << endl;
for (i = 0; i < nums; i++)
{
temp= s[i].last + "," + s[i].first;
cout << "last, first " << temp << endl;
outf << left << setw(20) << temp << right << setw(5)<< s[i].department << setw(5) << s[i].salary << setw(8) << endl;
}
outf << endl << endl;
}
void swap(sstruct &a, sstruct &b)
{
sstruct temp;
temp=a;
a=b;
b=temp;
}
void bubbleSort(sstruct s[50], int &nums)
{
int maxarray = 50;
int i, j;
bool swapped;
for (i = 0; i < nums - 1; i++)
{
swapped = false;
for (j = 0; j < nums - i - 1; j++)
{
if (s[j].department > s[j + 1].department)
{
swap(s[j], s[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int main() {
int nums=0;
double average3=0.0;
const int maxarray = 50;
sstruct s[maxarray];
init2(s);
print(s, nums, average3);
read(s, nums);
cout << "numsfirst: " << nums << endl;
avg(s, nums, average3);
cout << "nums" << nums << endl;
bubbleSort(s,nums);
print(s, nums, average3);
system("pause");
return 0;
}
I'm trying to implement a timer class which prints the time needed for a given scope. Somehow I can't get it to work properly. My code so far:
Main.cpp:
#include "scopetimer.hpp"
#include <cstdlib>
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
void work01()
{
double numbers[10000];
for (int i = 0; i < 10000; ++i)
{
numbers[i] = double(std::rand()) / double(RAND_MAX);
}
for (int n = 10000; n > 1; n = n - 1) {
for (int i = 0; i < n - 1; i = i + 1) {
if (numbers[i] > numbers[i + 1]) {
double tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = tmp;
}
}
}
}
void work02()
{
int* buf[1024];
for (int i = 2; i < 1024; ++i)
buf[i] = new int[i];
for (int i = 2; i < 1024; ++i)
delete[] buf[i];
}
// counts the number of primes in an interval
int work03(int n0, int n1)
{
int freq = n1 - n0 + 1;
for (int i = n0; i <= n1; ++i)
{
// Have fun: use the alternative iteration direction and see how fast
// it gets!
// for(int j = 2; j < i; ++j)
for (int j = i - 1; j > 1; --j)
{
if (i%j == 0)
{
--freq;
break;
}
}
}
return freq;
}
int main(int, char**)
{
{ ScopeTimer("work01");
work01();
}
{
ScopeTimer("work02");
work02();
}
{
ScopeTimer("work03");
work03(0, 10000);
}
std::cout << std::endl << "Tests" << std::endl << std::endl;
{
clock_t start_(std::clock());
work01();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work02();
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
{
clock_t start_(std::clock());
work03(0,10000);
clock_t end_(std::clock());
std::cout << "Test Timer: " << end_ - start_ << "ns" << std::endl;
}
system("Pause");
}
scopetimer.cpp
#include "scopetimer.hpp"
#include <cmath>
#include <string>
#include <chrono>
#include <iostream>
ScopeTimer::ScopeTimer(const std::string& name)
:name_(name),
start_(std::clock()) {
}
ScopeTimer::~ScopeTimer() {
double elapsed = (double(std::clock() - start_) / double(CLOCKS_PER_SEC));
std::cout << name_ << ": " << int(elapsed) << "ns" << std::endl;
}
I tested the clock functions outside of ScopeTimer(), which works fine. So the only issues, as far as I can tell, is that I can't get ScopeTimer() to work. It always prints 0ns. I mostly followed the turorial: https://felix.abecassis.me/2011/09/cpp-timer-raii/
Kind regards
In ~ScopeTimer() you print how many complete seconds have passed not how many nanoseconds, while in the second part of main, you print the number of clock ticks, which may or may not be the same as a nanosecond.
I came across the same problem
The solution for me is to define a ScopeTimer instance instead of just call its constructor, I mean:
{
ScopeTimer _scopetimer("work01");
work01();
}
That should work
I guess compiler seems to ignore (optimize) that, 'cause when you just call ScopeTimer("work01").
I'm trying to write a little program to create a vector of random integer sets, but the problem is once the first set is created the program keeps storing the same set of numbers in subsequent iterations. Any help to explain or correct this problem would be very much appreciated. Thanks!
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<set>
#include<vector>
using namespace std;
typedef set<int> Set_I;
typedef set<int>::iterator It;
typedef vector<set<int> > vec_Set;
int random();
void print_set(Set_I s);
void print_vec(vec_Set v);
int main()
{
srand(time(0));
Set_I s;
vec_Set v;
v.resize(4);
for(int i=0; i<4;i++)
{
//cout << s.size() << " " <<endl;
while(s.size()<6)
{
s.insert(random());
}
v[i] = s;
s.empty();
}
//print_set(s);
print_vec(v);
cout << endl << s.size() <<endl << v.size();
system("PAUSE");
}
int random()
{
int r = 1 + rand()%49;
return r;
}
void print_set(Set_I s)
{
for(It it=s.begin(); it!=s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void print_vec(vec_Set v)
{
for(int i=0;i<v.size();i++)
{
cout << "{ ";
for(It j = v[i].begin() ; j != v[i].end() ;j++)
{
cout << *j << " ";
}
cout <<"}";
cout <<endl;
}
}
s.empty() returns a bool stating that the set is empty or not. It has no effect on the members of the set!!
you have to use s.clear() for emptying (clearing) your set.
so my program is supposed to use one 5 sized array to store inputted integers. If it's a duplicated integer it would not be stored into the array.
The problem here is there would be 0's in my array indefinitely since i initialized the size to 5. I need to output only the unique numbers how would i do so?
One thing i noticed was that without my unsigned int position; whenever i enter a duplicate integer it would skip the index;
e.g. array[0] = 10, array[1] = 10 // duplicate, array[2] = 20 // inputted 20, this should've been stored into array[1] but it doesn't.
So i had the position to only increment whenever it's not a duplicate to make sure it's not skipping over the index when a duplicate is entered.
And was there anything i could've done or do a different approach to get my result?
Code:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
array <int, arraySize> numberArray = {};
template<size_t size>
bool isDuplicate(array<int, size> array, int value)
{
for (unsigned int i = 0; i < array.size(); i++)
{
if (value == array[i])
{
return true;
}
}
return false;
}
int main()
{
unsigned int input;
unsigned int position = 0;
for (unsigned int i = 0; i < arraySize; i++)
{
cout << "Enter # " << (i + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE)
{
cout << "The number entered is not in valid range of 10 to 100" << endl;
--i;
}
else if (!isDuplicate(numberArray, input))
{
numberArray[position] = input;
position++;
cout << "The number: " << input << " is unique\n" << endl;
}
}
}
Thanks!
The only missing part in your code is an additional block below your else if block:
else {
cout << "The number: " << input << " is not unique\n" << endl;
--i;
}
where you would decrease your position when the value is a duplicate, and warn the user about it.
If I had to update your program while keeping the most of your code I would write:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
// Initialize all array values to 0 (see std::array documentation)
array <int, arraySize> numberArray = {0};
template<size_t size>
bool isDuplicate(array<int, size> arr, int val)
{
bool ret = false;
// Do not waste time with invalid values
if (val < MIN_VALUE || val > MAX_VALUE)
return ret;
// Using size_t to express size
size_t pos = 0;
// Loop until reaching the end OR a not yet set array value
while ( pos < arr.size() && arr[pos]){
if (arr[pos] == val) {
// Found!
ret = true;
break;
}
++pos;
}
return ret;
}
int main()
{
unsigned int input = 0;
size_t position = 0;
while (position < numberArray.size()) {
cout << "Enter # " << (position + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE) {
cout << "The number entered is not in valid range of 10 to 100" << endl;
} else if (!isDuplicate(numberArray, input)) {
numberArray[position] = input;
// Pre-increment operator is more efficient, see doc.
++position;
cout << "The number: " << input << " is unique\n" << endl;
} else {
cout << "The number: " << input << " is not unique\n" << endl;
}
}
}
It looks like an exercise with a really weird specification. It should be better explained so as to give you a more relevant real-life solution. ;)
Hope this helps.