Problem with vector push_back
Jan 18, 2012 at 10:10pm UTC
Hello. I am trying to get the locations of certain letters from a string into a vector. However there is something wrong. I can't seem to get the right number into the vector as every dimension is still at 0. What i'm i doing wrong?
The code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
#include <iostream>
#include "string.h"
#include <fstream>
#include "conio.h"
#include <vector>
using namespace std;
int main()
{
char iword[200];
string iword2, astring;
int ilength=0, acount=0, ecount=0, icount=0, jcount=0, dcount=0;
iword2=iword;
ilength=iword2.length();
cin.get(iword, sizeof (iword)); cin.ignore(1000, '\n' );
for (int i=0; i<ilength; i++){
if (iword[i]=='A' ){
iword[i]='H' ;}
else if (iword[i]=='B' ){
iword[i]='i' ;}
else if (iword[i]=='C' ){
iword[i]='N' ;}
else if (iword[i]=='D' ){
iword[i]='T' ;}
else if (iword[i]=='E' ){
iword[i]='p' ;}
else if (iword[i]=='F' ){
iword[i]='f' ;}
else if (iword[i]=='G' ){
iword[i]='P' ;}
else if (iword[i]=='H' ){
iword[i]='e' ;}
else if (iword[i]=='I' ){
iword[i]='v' ;}
else if (iword[i]=='J' ){
iword[i]='A' ;}
else if (iword[i]=='K' ){
iword[i]='S' ;}
else if (iword[i]=='L' ){
iword[i]='F' ;}
else if (iword[i]=='M' ){
iword[i]='q' ;}
else if (iword[i]=='N' ){
iword[i]='l' ;}
else if (iword[i]=='O' ){
iword[i]='t' ;}
else if (iword[i]=='P' ){
iword[i]='D' ;}
else if (iword[i]=='Q' ){
iword[i]='g' ;}
else if (iword[i]=='R' ){
iword[i]='f' ;}
else if (iword[i]=='S' ){
iword[i]='e' ;}
else if (iword[i]=='T' ){
iword[i]='B' ;}
else if (iword[i]=='U' ){
iword[i]='j' ;}
else if (iword[i]=='V' ){ //bcdehkmnrsu EGIJKLMOQRUV
iword[i]='C' ;}
else if (iword[i]=='X' ){
iword[i]='o' ;}
else if (iword[i]=='Y' ){
iword[i]='a' ;}
else if (iword[i]=='Z' ){
iword[i]='f' ;}
}
vector<int >a_vector(20);
for (int i=0; i<ilength; i++){
if (iword[i]=='H' ){
acount++;
a_vector.push_back(i);
}
}
for (int i=0; i<20; i++){
try {
cout<<"Element " <<i<<": " <<a_vector.at(i);
}
catch (exception& e){
cout<<"\n\nElement: " <<i<< "Index exceeds vector dimensions." <<endl;
}
}
cout<<endl<<iword;
Last edited on Jan 18, 2012 at 10:13pm UTC
Jan 18, 2012 at 10:12pm UTC
push_back
adds to the end of the vector. Since the vector was size 20 to start with, you're adding them after those positions.
Topic archived. No new replies allowed.