11

私はこのようなことをしたいです。これを簡単に行う stl アルゴリズムはありますか?

 for each(auto aValue in aVector)
                {
                aMap[aValue] = 1;
                }
4

8 に答える 8

14

多分このように:

std::vector<T> v;   // populate this

std::map<T, int> m;

for (auto const & x : v) { m[x] = 1; }
于 2013-04-09T21:36:42.473 に答える
0

これを試して:

for (auto it = vector.begin(); it != vector.end(); it++) {
  aMap[aLabel] = it;
  //Change aLabel here if you need to
  //Or you could aMap[it] = 1 depending on what you really want.
}

これがあなたがやろうとしていることだと思います。

編集: の値を更新する場合はaLabel、ループ内で変更できます。また、元の質問を振り返ってみると、彼が何を望んでいるのか不明だったので、別のバージョンを追加しました。

于 2013-04-09T21:30:24.593 に答える
0

ベクター内のアイテムが順番に関連付けられていると仮定すると、次の例が役立つ可能性があります。

#include <map>
#include <vector>
#include <string>
#include <iostream>

std::map<std::string, std::string> convert_to_map(const std::vector<std::string>& vec)
{
    std::map<std::string, std::string> mp;
    std::pair<std::string, std::string> par;

    for(unsigned int i=0; i<vec.size(); i++)
    {
        if(i == 0 || i%2 == 0)
        {
            par.first = vec.at(i);
            par.second = std::string();
            if(i == (vec.size()-1))
            {
                mp.insert(par);
            }
        }
        else
        {
            par.second = vec.at(i);
            mp.insert(par);
        }
    }

    return mp;
}

int main(int argc, char** argv)
{
    std::vector<std::string> vec;
    vec.push_back("customer_id");
    vec.push_back("1");
    vec.push_back("shop_id");
    vec.push_back("2");
    vec.push_back("state_id");
    vec.push_back("3");
    vec.push_back("city_id");

    // convert vector to map
    std::map<std::string, std::string> mp = convert_to_map(vec);

    // print content:
    for (auto it = mp.cbegin(); it != mp.cend(); ++it)
        std::cout << " [" << (*it).first << ':' << (*it).second << ']';

    std::cout << std::endl;

    return 0;
}
于 2017-10-02T16:55:50.677 に答える