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.
Related
This question already has answers here:
How do I print out the contents of a vector?
(31 answers)
Closed 5 years ago.
I am trying to get a feel for C++, and I want to either print the contents of a vector, or, to confirm my program is correct, I could add the contents of my vector and print the result.
Here is my code:
#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
int main(){
int n;
vector<int> result;
cin >> n;
vector<int> numbers(n);
for(int i = 0; i < n; ++i){
cin >> numbers[i];
}
result = numbers;
cout << result;
return 0;
}
I found some solutions online for printing a vector, but I didn't understand what the code was doing, so I am hoping someone can help.
As you mentioned "I did not understand what the code is doing", let me briefly describe how to iterate through a container:
The long way:
vector<int> result = { 1,2,3 };
for (vector<int>::iterator it = result.begin(); it != result.end() ; it++) {
int i = *it;
cout << i << " ";
}
Each container provides an iterator, which you can think of a pointer moving forward along the elements of the container. begin() returns a pointer to the first element, end() returns a pointer to 1 past the last element. Dereferencing the iterator gives the actual value.
For above long way, with range-based for loops, C++ provides a shorthand notation with about the same meaning (i.e. it makes use of the iterator-concept but is less "clumsy" in notation):
for (auto i : result) {
cout << i << " ";
}
Try it out; hope it helps.
you can print the vector content by making a loop the print every index in the vector size
like
for(int i=0;i<numbers.size();i++){
cout<<numbers[i];
}
the loop will print every index until the end of the vector
#include <iostream>
#include <vector>
int main()
{
unsigned int numVec;
unsigned int input;
std::cout << "Enter Number of Vectors: ";
std::cin >> numVec;
std::vector<int>* Vec;
for (unsigned int i = 0; i < numVec; i++)
{
std::cout << "Enter Vector Value " << i << ": ";
std::cin >> input;
Vec->push_back(input);
}
std::cout << std::endl;
for (unsigned int i = 0; i < Vec->size(); i++)
{
std::cout << "Value at Index (" << i << ") " << Vec->at(i) << std::endl;
}
std::cout << std::endl;
return 0;
}
I am trying to learn how Vectors work as it is a topic that i have withheld learning for a very long time for no apparently reason.
My above code will compile and run however once i put in a number to store in the Vector it will crash.
The program did work before when i was just using a vector without the pointer but just for learning reasons i wanted to try it with a pointer, I am just wondering what am i doing wrong with this code and if someone could possibly flame me for doing something or give me some good advice on what i am doing wrong in this situation so i can learn for future reference.
Replace
std::vector<int>* Vec;
with
std::vector<int> vec;
and replace the pointer to member operator -> with the member selection operator ..
Only on rare occasions do you need to use dynamic storage for a std::vector instance, as that class does an excellent job of managing the memory for you. Currently you are not allocating any memory for your vector, and the behaviour of your code is undefined.
If you must use a pointer then write
std::vector<int>* vec = new std::vector();
and don't forget to call delete vec; when you're done. Consider using std::unique_ptr &c. so the delete is taken care of automatically.
My above code will compile and run however once i put in a number to store in the Vector it will crash.
What vector?
You never created a vector.
You only created a pointer, one which (a) is uninitialised, and (b) does not point to anything, let alone a (c) vector.
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
I am having trouble accessing data inside a map using an iterator. I want to return all of the values inserted into the map by using an iterator. However, when I use the iterator, it doesn't acknowledge any of the members in the instance of the class it has been past into.
int main()
{
ifstream inputFile;
int numberOfVertices;
char filename[30];
string tmp;
//the class the holds the graph
map<string, MapVertex*> mapGraph;
//input the filename
cout << "Input the filename of the graph: ";
cin >> filename;
inputFile.open(filename);
if (inputFile.good())
{
inputFile >> numberOfVertices;
inputFile.ignore();
for (int count = 0; count < numberOfVertices; count++)
{
getline(inputFile, tmp);
cout << "COUNT: " << count << " VALUE: " << tmp << endl;
MapVertex tmpVert;
tmpVert.setText(tmp);
mapGraph[tmp]=&tmpVert;
}
string a;
string connectTo[2];
while (!inputFile.eof())
{
//connectTo[0] and connectTo[1] are two strings that are behaving as keys
MapVertex* pointTo;
pointTo = mapGraph[connectTo[0]];
pointTo->addNeighbor(mapGraph[connectTo[1]]);
//map.find(connectTo[0]).addNeighbor(map.find(connectTo[1]));
//cout << connectTo[0] << "," << connectTo[1] << endl;
}
map<string,MapVertex*>::iterator it;
for (it=mapGraph.begin(); it!=mapGraph.end(); it++)
{
cout << it->getText() << endl;
}
}
return 0;
}
Compiler output:
\lab12\main.cpp||In function `int main()':|
\lab12\main.cpp|69|error: 'struct std::pair<const std::string, MapVertex*>'
has no member named 'getText'|
||=== Build finished: 1 errors, 0 warnings ===|
There is an access member in my MapVertex class called getText() which returns the data that is inside it.
To fix the compiler error, you need to do it->second->getText() as the *iterator is a pair<string, MapVertex*>. But there are other problems in your code. While inserting into the map, you are inserting the address of a local variable into it. This address will be invalid by the time you try to iterate the map using for loop. I would suggest you to declare the map as std::map<string, MyVertex> so that when you insert into the map a copy of the MyVertex is inserted into map.
tmpVert is the problem. Look, you create it on the stack. It is destroyed at the end of each for loop.
It Is Destroyed.
So, your mapGraph is holding pointers to objects that don't exist.
'struct std::pair' has no member named 'getText'
means that what the iterator returns is std::pair, not your object directly; the first element of the pair is the key, the second the value, so you need to get the value, and then call the method: it->second->method().
The Vector find function can search an inserted value even if you try and find by providing substring . Is this same in case of the keys of a map ?
int main()
{
vector<string> v;
v.push_back("text");
v.push_back("[[text");
v.push_back("text");
for (unsigned i = 0; i < v.size(); i++)
{
if (v[i].find("[[") == 0)
{
v[i].append("]]");
}
}
}
Here it finds "[[text" and makes it "[[text]]" .
I tried it in map but code crashes on run time ,. I am using Dev c++
int main()
{
std::multimap<string, string> m;
std::multimap<string, string> intersection;
std::multimap<string, string>::iterator it8;
m.insert(pair< string, string>("4-2"," 61-7" ));
m.insert(pair< string, string>("5-2"," 61-7" ));
multimap<string, string>::iterator it4;
multimap<string, string>::iterator it5;
for ( it4 = m.begin(); it4 !=m.end(); it4++)
{
if (m.find("5-") == 0)
it5=it4;
}
cout << " result of 5 search is" << (*it5).first << ", " << (*it5).second <<endl;
m.clear();
getchar();
}
(Sample correct code on ideone)
The error is that this line
if (m.find("5-") == 0)
will never succeed. You maybe be surprised at this. m.find("5-") searches through the entire map looking for an entry whose key is exactly equal to "5-". Your keys are "4-2" and "5-2".
Do you wish to find keys which contain the substring "5-"? Then you need something like
it4->first.find("5-"); // check if the key string at this entry contains "5-"
I think you want a loop like this:
multimap<string, string>::iterator it4;
for ( it4 = m.begin(); it4 !=m.end(); it4++)
{
if (it4->first.find("5-") != string :: pos)
cout << " result of 5 search is" << it4->first << ", " << it4->second <<endl;
}
As others have pointed out, you are not interested in the the find method of vector or map. You are interested in the find method of string - this is quite different. The title of your question is a little misleading as a result (unintentionally).
The problem with std::set<> is that you cannot modify its elements in place because you could violate the ordering it has. You can however iterate from set.begin() to set.end() using iterators (instead of operator[]) and remove and reinsert modified elements.