替换矢量中的字符串而不进行定位

时间:2014-05-22 15:27:50

标签: c++ vector fstream

在我正在处理的代码中,我现在有一个来自txt文件的向量加载现在我试图看看它们是否可以替换向量中的某些单词而无需位置或任何内容 所以例如,如果txt包含一个动物列表,我想改变鸟类预订我将如何做到这一点,而不需要字母的位置

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

vector <string> test;

int main()
{
  string file;
  fstream fout( "Vector.txt" );
  while  ( !fout.eof())
  {
   getline(fout,file);
   test.push_back(file);
  }
  fout.close();


  for( int i = 0; i < test.size(); i++)
  {
   cout << test[i] << endl;
  }


  system("pause");
}

txt包含:




河马

4 个答案:

答案 0 :(得分:2)

使用std::transform()

std::string bird2book(const string &str)
{
    if (str == "bird")
        return "book";
    return str;
}

std::transform(test.begin(), test.end(), test.begin(), bird2book);

答案 1 :(得分:1)

您可以使用std::replace

std::replace (test.begin(), test.end(), "bird", "book"); 

答案 2 :(得分:0)

使用STL !!这是我们的力量。你需要的一切:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <fstream>
#include <map>

int main()
{
    std::vector<std::string> words;

    const std::map<std::string, std::string> words_to_replace{
            { "bird", "book" }, { "cat", "table" }
        };
    auto end = words_to_replace.cend();

    std::transform(
        std::istream_iterator<std::string>{ std::ifstream{ "file.txt" } },
        std::istream_iterator<std::string>(),
        std::back_inserter(words),
        [&](const std::string& word) {
            auto word_pos = words_to_replace.find(word);
            return (word_pos != end) ? word_pos->second : word;
        });

    std::copy(words.cbegin(), words.cend(),
        std::ostream_iterator<std::string>(std::cout, "\n"));
    std::cout << std::endl;
}

答案 3 :(得分:0)

试试这个:

typedef std::istream_iterator<string> isitr;

ifstream fin("Vector.txt");
vector <string> test{ isitr{fin}, isitr{} }; // vector contains strings

map<string,string> dict{ // replacements dictionary
    {"bird", "book"}, {"cat", "kitten"}
};

for(auto& x: test) // x must be a reference
{
    auto itr = dict.find(x);
    if(itr != dict.end()) // if a match was found
        x = itr->second; // replace x with the found replacement
                         // (this is why x must be a reference)
}

for(const auto& x: test)
    cout << test << " ";