Was hoping to print out the values of test1. I just would like to ask how come the values of test1 are not printed out and only prints out "PRINT START" and "PRINT END". Any help or idea is highly appreciate.
#include <vector>
#include <iostream>
using namespace std;
void print_out(vector<int> numbers)
{
cout << "------------- PRINT START -------------" << endl;
for( auto i: numbers )
cout << i << endl;
cout << "------------- PRINT END -------------" << endl;
}
vector<int> beautify(vector<string> numbers)
{
vector<int> result;
return result;
}
int main()
{
vector<string> test1;
test1.push_back("3167389213");
test1.push_back("32989741893");
test1.push_back("2138");
print_out(beautify(test1));
return 0;
}
Update
Thank you, So I've applied the codes inside beautify though it still cant output the test1 values.
vector<int> beautify(vector<string> numbers)
{
vector<int> result;
for (auto & i : numbers)
result.push_back(std::stoi(i));
return result;
}
Ok, this is the flow of your program:
you create an empty vector
you fill it with strings that contains digits
you call the print_out function with the argument beautify(test1) so we need to look what beautify() returns.
beautify() returns an empty vector (int)
print_out() prints all elements from the empty vector, so none.
This code is equivalent and maybe clarifies something:
int main()
{
vector<string> test1;
test1.push_back("3167389213");
test1.push_back("32989741893");
test1.push_back("2138");
vector<int> newVector = beautify(test1);
print_out(newVector); //here newVector is empty
return 0;
}
What you probably want to do is in your beautify() function, convert the string vector to an int vector. See How do I convert vector of strings into vector of integers in C++?
Correct your beautify function
vector<int> beautify(vector<string> numbers)
{
vector<int> result;
for (auto & i : numbers)
result.push_back(std::stoi(i));
// If results are to be sorted
std::sort(result.begin(), result.end());
return result;
}
Also, the integers that you push in form of strings are out of range.
test1.push_back("3167389213"); // outside the range of int
test1.push_back("32989741893");
See http://ideone.com/vOeMHi demo
Related
I'm trying to get a vector of string from input to create a graph , but i don't know why in middle my code it crashes. please help me fix it. I use Visual Studio.
#include <iostream>
#include <vector>
#include <iterator>
void main(void)
{
{
using namespace std;
int8_t n{ 0 };
cout << "enter the size of graph : ";
cin >> n;
vector<string> graph(n);
string connectionsWith;
vector<string>::iterator i;
string::iterator e;
int p{ 0 };
for (i = graph.begin(); i != graph.end(); ++i)
{
cout << '\n' << "enter the vertices that are connected to " << p << " : ";
cin >> connectionsWith;
graph.push_back(connectionsWith);
p++;
}
p = 0;
for (i = graph.begin(); i != graph.end(); ++i)
{
cout << p << " is connected to " << *i;
p++;
}
}
}
In your constructor of graph, you allocate n string. Inside the loop you add on top of the constructed n strings, n more strings via push back. That potentially invalidates your iterators, as ChrisMM said, also not the most efficient way to implement such a scenario.
So as a solution, instead of
vector<string> graph(n);
do
vector<string> graph;
graph.reserve(n);
and iterate over the index, e.g. from 0 to n, and push back.
Especially in the first loop you are not dereferencing the iterator at all, which suggests that using index based loop would show your intent better.
life_steal pointed out the problem. I would like to add few information and other way to solve the problem.
int8_t n{ 0 };
vector<string> graph(n); // Here initialization happening with ASCII. If input is "1" then it would be "49". Consider changing int8_t to int if you unaware of that.
graph.push_back(connectionsWith); //Instead of this line Use: *i = connectionsWith; it directly assign the value.
I want to sort some strings of the same size. The size of the string can be very large(10^18). How can I sort all the stings in less possible time? The size of all the inputted string will be equal. How can I sort these strings in less amount of time possible?
922003001020293839297830207344987344973074734
766352786207892397340783784078348747606208602
182823068326283756515117829362376823572395775
//the size of all the strings are equal
Can anyone please explain a better way of sorting?
Thanks Your any help will be highly appreciated.
Here it's done with std::sort from the header algorithm
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main(){
std::vector<std::string> nums{
"922003001020293839297830207344987344973074734",
"766352786207892397340783784078348747606208602",
"182823068326283756515117829362376823572395775"
};
std::cout << "unsorted: " << std::endl;
for (auto i : nums){
std::cout << i << std::endl;
}
std::sort(nums.begin(), nums.end()); //sort it
std::cout << "\nsorted: " << std::endl;
for (auto i : nums){
std::cout << i << std::endl;
}
system("pause");
return 0;
}
output:
unsorted:
922003001020293839297830207344987344973074734
766352786207892397340783784078348747606208602
182823068326283756515117829362376823572395775
sorted:
182823068326283756515117829362376823572395775
766352786207892397340783784078348747606208602
922003001020293839297830207344987344973074734
It just so happens to be that a string containing only digits is alphabetically sortable, so you just put each string into a vector, and simply sort the vector.
As noted, this only works if the "numbers" all have the same number of digits. Else you need pad the strings with leading zeroes so they are all of the same length. The leading zeroes can then be removed once you have sorted the vector.
I'm doing some exercises with vectors. I created a function that fill a vector with defined size but when I tried to make it n size, the vector apparently is filled with trash memory, it shows: 0x23fe20, and my code crash when I try to use the vector.
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int cargavn(int vec[]) // fill vector
{
int i, t;
cout << "vector size: ";
cin >> t;
for(i = 0 ; i <= t-1; i++)
{
cout << "v["<< i <<"]=";
cin >> vec[i];
}
return (1);
}
int main()
{
int vec[10]; // the vector, size here wont matter
cargavn(vec); // call fill vector n positions
cout << vec; // to test if the vector is well filled
system("PAUSE");
}
you are exprecting cout << vec to somehow pretty print the vector. It wont, it just prints its address
You need to loop over the contents and print each element
for(int i =0 ; i < 10 ; i++)
{
cout << vec[i];
}
Here's how it would look using modern C++:
#include <iostream>
#include <vector>
using namespace std;
void cargavn(vector<int> &vec)
{
int t;
cout << "vector size: ";
cin >> t;
for(int i = 0; t > 0; ++i, --t)
{
cout << "v["<< i <<"]=";
int v;
cin >> v;
vec.push_back(v);
}
}
ostream &operator<<(ostream &s, vector<int> const &vec)
{
s << '{';
bool first = true;
for (int v : vec)
{
if (!first)
{
s << ", ";
}
s << v;
first = false;
}
return s << '}';
}
int main()
{
vector<int> vec;
cargavn(vec);
cout << vec;
system("PAUSE");
return 0;
}
Things to understand about this version compared to yours:
Unnecessary includes are ommitted.
Prefer C++ containers like vector over C style arrays.
Use dynamically sized containers when they need to hold an arbitrary number of values provided by the user instead of fixed-size containers that break when the user enters too much data. See the rule of 0, 1, infinity.
When all control paths of a function return the same value, then the returned value is pointless and can be omitted. Particularly if none of the callers even bothers to check the return value. I suspect you had the intention of using the return value to indicate some kind of unexpected error. This is a C-style approach to error handling. C++ uses exceptions to deal with unexpected errors.
Overload operator<< to extend the stream insertion operator to decide how containers and your own custom types should be formatted. The standard library doesn't provide any such insertion operator for vector because there isn't any universally agreed upon way to decide how a vector of values should be formatted. So you decide this for yourself.
It is good form for main to return a value, even though this is not technically required.
I would like to parse through two vectors of strings and find the strings that match each other and the ones that do not.
Example of what I want get:
input vector 1 would look like: [string1, string2, string3]
input vector 2 would look like: [string2, string3, string4]
Ideal output:
string1: No Match
string2: Match
string3: Match
string4: No Match
At the moment I use this code:
vector<string> function(vector<string> sequences, vector<string> second_sequences){
for(vector<string>::size_type i = 0; i != sequences.size(); i++) {
for(vector<string>::size_type j = 0; j != second_sequences.size(); j++){
if (sequences[i] == second_sequences[j]){
cout << "Match: " << sequences[i];
}else{
cout << "No Match: " << sequences[i];
cout << "No Match: " << second_sequences[j];
}
}
}
}
It works great for the ones that match, but iterates over everything so many times,
and the ones that do not match get printed a large number of times.
How can I improve this?
The best code is the code that you did not have to write.
If you take a (STL) map container it will take care for you of sorting and memorizing the different strings you encounter.
So let the container works for us.
I propose a small code quickly written. You need for this syntax to enable at least the C++ 2011 option of your compiler ( -std=c++11 on gcc for example ). The syntax that should be used before C++11 is much more verbose (but should be known from a scholar point of view ).
You have only a single loop.
This is only a hint for you ( my code does not take into account that in the second vector string4 could be present more than once, but I let you arrange it to your exact needs)
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
vector<string> v1 { "string1","string2","string3"};
vector<string> v2 { "string2","string3","string4"};
//ordered map will take care of "alphabetical" ordering
//The key are the strings
//the value is a counter ( or could be any object of your own
//containing more information )
map<string,int> my_map;
int main()
{
cout << "Hello world!" << endl;
//The first vector feeds the map before comparison with
//The second vector
for ( const auto & cstr_ref:v1)
my_map[cstr_ref] = 0;
//We will look into the second vector ( it could also be the third,
//the fourth... )
for ( const auto & cstr_ref:v2)
{
auto iterpair = my_map.equal_range(cstr_ref);
if ( my_map.end() != iterpair.first )
{
//if the element already exist we increment the counter
iterpair.first->second += 1;
}
else
{
//otherwise we put the string inside the map
my_map[cstr_ref] = 0;
}
}
for ( const auto & map_iter: my_map)
{
if ( 0 < map_iter.second )
{
cout << "Match :";
}
else
{
cout << "No Match :" ;
}
cout << map_iter.first << endl;
}
return 0;
}
Output:
No Match :string1
Match :string2
Match :string3
No Match :string4
std::sort(std::begin(v1), std::end(v1));
std::sort(std::begin(v2), std::end(v2));
std::vector<std::string> common_elements;
std::set_intersection(std::begin(v1), std::end(v1)
, std::begin(v2), std::end(v2)
, std::back_inserter(common_elements));
for(auto const& s : common_elements)
{
std::cout<<s<<std::endl;
}
Since I am beginner to c++, I was trying to play with . So, I succeeded in
map<string,int>
And,
map <string, vector<int> >
But, I was curious if having two vectors in a map can be accessible. So, what should I do?
int main()
{
map<vector<string>,vector<int> > a;
vector<int> okay;
vector<string> knot;
knot.push_back("name1"); //this for inserting in vector<string>
knot.push_back("name2");
okay.push_back(1); //this on for vector<int>
okay.push_back(2);
a[knot]=okay;
map<vector<string>,vector<int> >::iterator i=a.begin();
cout<<i->first<<endl; //error shows here, how am i accessing this?
++i;
cout<<i->first; //this too. Function resembles the same of above. So, ERROR!!
return 0;
}
This line:
cout<<i->first<<endl;
You are doing the right thing, but i->first returns a vector because you have a map of vectors. There is no overloaded << (print) operator for vector<string> (but you could make your own). But if you:
auto temp = i->first;
for(const auto &a : temp) {
cout << a << endl;
}
This will print all the elements stored in the vector in i->first.
If you wish the print the first element stored in the vector, you can do:
cout << *((i->first).begin()) << endl; //iterator method or
cout << (i->first)[0] << endl;
Do not attempt to print vector elements without checking emptiness.